linqToXml比較的靈活和方便,它是基於函數式編程
具體的使用如下:
引用程序集using System.Xml.Linq;
1、創建XDocument並設置文檔頭
XDocument XDoc = new XDocument();
XDoc .Declaration = new XDeclaration("1,0", "gb2312", null);
2、創建根節點元素XElement
XElement root = new XElement("root");//創建節點
XDoc .Add(root);//添加子節點
3、創建子節點並添加屬性
//類似於dom模式創建
XElement stu= new XElement("Student");//創建Student節點
XAttribute id= new XAttribute("id", "001");//創建屬性id並設置值為"001"
stu.add(id);//為stu節點添加id屬性
//鏈式模式創建
XElement stu= new XElement("Student", new XAttribute("id", "001"));
4、為Student創建子節點(三種創建方法)
XElement name = new XElement("Name");
XText xt = new XText("張三");
name.Add(xt);
XElement age = new XElement("Age");
age.Value = "12";
XElement gender = new XElement("Gender", "男");
5、保存
XDoc .Save("xxx.xml");
完整的鏈式創建
new XDocument(new XDeclaration("1.0", "gb2312", null), new XElement("root", new XElement("Student", new XAttribute("id", "001"), new XElement("Name", "張三"), new XElement("Age", "12"), new XElement("Gender", "男")))).Save("xxx.xml");
生成結果:
<?xml version="1.0" encoding="gb2312"?>
<root>
<Student id="001">
<Name>張三</Name>
<Age>12</Age>
<Gender>男</Gender>
</Student>
</root>