XML文件读写

xml文件内容

<?xml version=”1.0″ encoding=”utf-8″ standalone=”yes”?>

<library>

<book>

<name>笑傲江湖</name>

<name1>罪与罚</name1>

</book>

</library>

文件的读取


private
void button1_Click(object sender, EventArgs e)

{


OpenFileDialog op = new
OpenFileDialog();

op.Filter = “xml文件|*.xml”;

op.ShowDialog();

 


XDocument document = XDocument.Load( op.FileName );


XElement root = document.Root;


XElement book = root.Element(“book”);


XElement name1 = book.Element(“name”);


XElement name2 = book.Element(“name1”);


MessageBox.Show(name1.Value);


MessageBox.Show(name2.Value);

}

文件的写入


private
void button2_Click(object sender, EventArgs e)

{


OpenFileDialog op = new
OpenFileDialog();

op.Filter = “xml文件|*.xml”;

op.ShowDialog();

 


XDocument document = XDocument.Load(op.FileName);


XElement root = document.Root;


XElement book = root.Element(“book”);


XElement name1 = book.Element(“name”);


XElement name2 = book.Element(“name1”);

name1.Value = 笑傲江湖;

name2.Value = 罪与罚;

document.Save(op.FileName);

}