這個例子要把bookstore.xml文件增加一條book記錄
1 bookstore.xml
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
<book genre="love" ISBN="1234123">
<title>who am i </title>
<author>who</author>
<price>999</price>
</book>
</bookstore>
2 bookstore.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace toxml
{
public class ToXml
{
public static void Main(string[] args)
{
//實例化一個XmlDocument對象
XmlDocument xmlDoc = new XmlDocument();
//實例對象讀取要寫入的XML文件
xmlDoc.Load("bookstore.xml");
//查找<bookstore>
XmlNode root = xmlDoc.SelectSingleNode("bookstore");
//創建一個<book>節點
XmlElement xe1 = xmlDoc.CreateElement("book");
//設置該節點genre屬性
xe1.SetAttribute("leixing", "music");
//設置該節點ISBN屬性
xe1.SetAttribute("ISBN", "56756");
//設置標題子節點
XmlElement xesub1=xmlDoc.CreateElement("title");
//設置文本內容
xesub1.InnerText = "CS從入門到精通";
//將文本內容添加到<book>節點中
xe1.AppendChild(xesub1);
//添加作者子結點
XmlElement xesub2 = xmlDoc.CreateElement("author");
//設置作者名字
xesub2.InnerText = "候捷";
//將文本內容添加到<book>節點中
xe1.AppendChild(xesub2);
//添加價格子結點
XmlElement xesub3 = xmlDoc.CreateElement("price");
//設置價格
xesub3.InnerText = "222";
//將價格添加到<book>節點中
xe1.AppendChild(xesub3);
//添加到<bookstore>節點中
root.AppendChild(xe1);
//保存文件
xmlDoc.Save("bookstore.xml");
}
}
}
運行後的XML文件如下:
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
<book genre="love" ISBN="1234123">
<title>who am i </title>
<author>who</author>
<price>999</price>
</book>
<book leixing="music" ISBN="56756">
<title>CS從入門到精通</title>
<author>候捷</author>
<price>222</price>
</book>
</bookstore>