c# 操作XML
c# 操作XML
XML文件
<?xml version="1.0" encoding="utf-8"?>
<booklist>
<book>
<name>历史</name>
<auther>陈平</auther>
<pubdate>2009-6-7</pubdate>
</book>
<book ids="chen">
<name>历史</name>
<auther>chen ping</auther>
</book>
</booklist>
使用的命名空间:
using System.Xml;
//遍历
string strxml = "";
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath(@"book.xml"));
XmlNodeList xmllist = xmldoc.SelectNodes("booklist/book");
foreach (XmlNode xn in xmllist)
{
strxml += xn["name"].InnerText + xn["auther"].InnerText;
}
Response.Write(strxml);
//删除
XmlNode xmldel = xmldoc.SelectSingleNode("booklist");
XmlNodeList xmlist = xmldel.ChildNodes;
foreach (XmlNode xns in xmlist)
{
if (xns["name"].InnerText == "PhotoShop")
{
xmldel.RemoveChild(xns);
xmldoc.Save(Server.MapPath(@"book.xml"));
}
else
{
xns["name"].InnerText = "历史";
xmldoc.Save(Server.MapPath(@"book.xml"));
}
}
//添加
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath(@"book.xml"));
XmlNode root = xmldoc.SelectSingleNode("booklist");
XmlElement xPortName = xmldoc.CreateElement("book");
xPortName.SetAttribute("ids", "chen"); //添加属性
XmlElement xSubNode1 = xmldoc.CreateElement("name");
xSubNode1.InnerText = ".NET精通";
xPortName.AppendChild(xSubNode1);
XmlElement xSubNode2 = xmldoc.CreateElement("auther");
xSubNode2.InnerText = "chen jian ping";
xPortName.AppendChild(xSubNode2);
root.AppendChild(xPortName);
xmldoc.Save(Server.MapPath(@"book.xml"));
XML文件
<?xml version="1.0" encoding="utf-8"?>
<booklist>
<book>
<name>历史</name>
<auther>陈平</auther>
<pubdate>2009-6-7</pubdate>
</book>
<book ids="chen">
<name>历史</name>
<auther>chen ping</auther>
</book>
</booklist>
使用的命名空间:
using System.Xml;
//遍历
string strxml = "";
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath(@"book.xml"));
XmlNodeList xmllist = xmldoc.SelectNodes("booklist/book");
foreach (XmlNode xn in xmllist)
{
strxml += xn["name"].InnerText + xn["auther"].InnerText;
}
Response.Write(strxml);
//删除
XmlNode xmldel = xmldoc.SelectSingleNode("booklist");
XmlNodeList xmlist = xmldel.ChildNodes;
foreach (XmlNode xns in xmlist)
{
if (xns["name"].InnerText == "PhotoShop")
{
xmldel.RemoveChild(xns);
xmldoc.Save(Server.MapPath(@"book.xml"));
}
else
{
xns["name"].InnerText = "历史";
xmldoc.Save(Server.MapPath(@"book.xml"));
}
}
//添加
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath(@"book.xml"));
XmlNode root = xmldoc.SelectSingleNode("booklist");
XmlElement xPortName = xmldoc.CreateElement("book");
xPortName.SetAttribute("ids", "chen"); //添加属性
XmlElement xSubNode1 = xmldoc.CreateElement("name");
xSubNode1.InnerText = ".NET精通";
xPortName.AppendChild(xSubNode1);
XmlElement xSubNode2 = xmldoc.CreateElement("auther");
xSubNode2.InnerText = "chen jian ping";
xPortName.AppendChild(xSubNode2);
root.AppendChild(xPortName);
xmldoc.Save(Server.MapPath(@"book.xml"));