添加XML
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath("~") + "/test.xml");
XmlNode root = xmldoc.SelectSingleNode("bookstore");
XmlElement xe1 = xmldoc.CreateElement("book");
xe1.SetAttribute("genre", "张三");
xe1.SetAttribute("ISBN", "2-3631-4");
XmlElement xesub1 = xmldoc.CreateElement("title");
xesub1.InnerText = "C#从入门到精通";
xe1.AppendChild(xesub1);
XmlElement xesub2 = xmldoc.CreateElement("Author");
xesub2.InnerText = "侯捷";
xe1.AppendChild(xesub2);
XmlElement xesub3 = xmldoc.CreateElement("Price");
xesub3.InnerText = "69.8";
xe1.AppendChild(xesub3);
root.AppendChild(xe1);
xmldoc.Save(Server.MapPath("~/test.xml"));
修改XML
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath("~") + "/test.xml");
XmlNodeList NodeList = xmldoc.SelectSingleNode("bookstore").ChildNodes;
foreach (XmlNode node in NodeList)
{
XmlElement xe = (XmlElement)node;
Response.Write(xe.GetAttribute("genre"));
if (xe.GetAttribute("genre") == "Jack")
{
xe.SetAttribute("genre", "Update张三");
XmlNodeList xnl = xe.ChildNodes;
foreach (XmlNode xn in xnl)
{
XmlElement xe2 = (XmlElement)xn;
if (xe2.Name == "Author")
{
Response.Write(xe2.InnerText);
xe2.InnerText = "李四";
break;
}
}
}
}
xmldoc.Save(Server.MapPath("~") + "/test.xml");
删除XML节点
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath("~") + "/test.xml");
XmlNodeList nodeList = xmldoc.SelectSingleNode("bookstore").ChildNodes;
foreach (XmlNode node in nodeList)
{
XmlElement xe = (XmlElement)node;
if (xe.GetAttribute("genre") == "fantasy")
{
xe.RemoveAttribute("genre");
}
if (xe.GetAttribute("genre") == "张三")
{
xe.RemoveAll();
}
}
xmldoc.Save(Server.MapPath("~") + "/test.xml");
读取XML
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath("~") + "/test.xml");
XmlNodeList NodeList = xmldoc.SelectSingleNode("bookstore").ChildNodes;
foreach (XmlNode xn in NodeList)
{
XmlElement xe = (XmlElement)xn;
Response.Write(xe.GetAttribute("genre") + "<br>");
Response.Write(xe.GetAttribute("ISBN") + "<br>");
XmlNodeList xnl = xn.ChildNodes;
foreach (XmlNode xn2 in xnl)
{
Response.Write(xn2.InnerText + "<br>");
}
}