1。XML(XMLFile.xml):
<?xml version="1.0" encoding="utf-8"?>
<company>
<employee>
<name>name1</name>
<sex>男</sex>
<age>17</age>
</employee>
</company>
1。读取
protected void btReadXML_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("XMLFile.xml"));
XmlNodeList nodes = doc.SelectSingleNode("company").ChildNodes;
//InnerXml:获取的是本节点中的XML字符串;
//InnerText:获取的是不带XML标记的字符串;
Response.Write(nodes.Item(0).InnerXml);
foreach (XmlNode node in nodes) {
foreach (XmlNode n in node.ChildNodes) {
//主:xml中的Value也相当于一级节点InnerText,
Response.Write(n.ChildNodes[0].Value+"<br>");
//相当于:
Response.Write(n.InnerText + "<br>");
}
}
}
2。写入并保存
protected void btWriteXml_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("XMLFile.xml"));
XmlNodeList nodes = doc.SelectSingleNode("company").ChildNodes;
nodes.Item(0).LastChild.InnerText = "17";
doc.Save(Server.MapPath("XMLFile.xml"));
}