/*参考代码(MSDN)*/
/*可用方法还有AppendChild(),问题是怎么把新的节点添加到现有的XML文档中某个节点之后*/
/*------------------------------------------------------------------------------------
*比如已有XML文件"D:\Summary.xml",怎么在文档中添加"<news2>"元素节点*/
*<MyDocument>
* <news1>
* <bianhao>012345</bianhao>
* <biaoti>Hello</biaoti>
* </news1>
*</MyDocument>
*-------------------------------------------------------------------------------------*/
using System;
using System.IO;
using System.Xml;public class Sample { public static void Main() { XmlDocument doc = new XmlDocument();
doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" +
"<title>Pride And Prejudice</title>" +
"</book>"); XmlNode root = doc.DocumentElement; //Create a new node.
XmlElement elem = doc.CreateElement("price");
elem.InnerText="19.95"; //Add the node to the document.
root.InsertAfter(elem, root.FirstChild); Console.WriteLine("Display the modified XML...");
doc.Save(Console.Out); }
}
//上面代码可以输出一个XML文件,请加各位高手怎么修改以上代码应用到已有XML文件
/*可用方法还有AppendChild(),问题是怎么把新的节点添加到现有的XML文档中某个节点之后*/
/*------------------------------------------------------------------------------------
*比如已有XML文件"D:\Summary.xml",怎么在文档中添加"<news2>"元素节点*/
*<MyDocument>
* <news1>
* <bianhao>012345</bianhao>
* <biaoti>Hello</biaoti>
* </news1>
*</MyDocument>
*-------------------------------------------------------------------------------------*/
using System;
using System.IO;
using System.Xml;public class Sample { public static void Main() { XmlDocument doc = new XmlDocument();
doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" +
"<title>Pride And Prejudice</title>" +
"</book>"); XmlNode root = doc.DocumentElement; //Create a new node.
XmlElement elem = doc.CreateElement("price");
elem.InnerText="19.95"; //Add the node to the document.
root.InsertAfter(elem, root.FirstChild); Console.WriteLine("Display the modified XML...");
doc.Save(Console.Out); }
}
//上面代码可以输出一个XML文件,请加各位高手怎么修改以上代码应用到已有XML文件
doc.Load("C:\\a.xml");XmlNode root = doc.DocumentElement;//Create a new node.
XmlElement elem = doc.CreateElement("price");
elem.InnerText="19.95";//Add the node to the document.
root.FirstChild.InsertAfter(elem, root.FirstChild.LastChild);Console.WriteLine("Display the modified XML...");
doc.Save("Console.Out");
应为
doc.Save(Console.Out);
把doc.Save(Console.Out);改为doc.Save("C:\\a.xml");可以把新建<price>节点添加到已有a.xml中
还有问题
<price>节点之外再建一个元素<news2>怎么写法?效果如下:
---------------------------------------------------------
* <news1>
* <bianhao>012345</bianhao>
* <biaoti>Hello</biaoti>
* </news1>
* <news2>
* <price>19.95</price>
* </news2>
把它插入指定元素内又怎么写法?
-----------
node.AppendChild()
如果要指定在某个元素之后(之前)那怎么写法?
-------------------------------------------------
//创建两个元素.
XmlElement elem = doc.CreateElement("news2");
elem.InnerText="";
XmlElement elem1 = doc.CreateElement("price");
elem1.InnerText="19.95";
//先插入"news2"元素,再把后一个元素嵌入其中
root.AppendChild(elem);
root.LastChild.InsertAfter(elem1,null);