- 创建XML文件
首先要加上引用using System.Xml.Linq;
然后声明一个XDocument实例,在构造函数中一定要先加上XDeclaration声明版本、编码方式和标识,然后层套加入XElement和XAttribute;
最后要记得保存XML文件。
示例:
XDocument doc=new XDocument();
XDeclaration dec=doc.CreateXmlDeclaration("1.0","utf-8","yes");
XElement root=doc.CreateElement("Root");//根节点
XElement node=doc.CreateElement("Node");//二级节点
XElement ele1=doc.CreateElement("Ele1");//三级节点
ele1.SetAttribute("attribute","attr1");
ele1.SetAttribute("attribute","attr2");
ele1.InnerText="Comment";
node.AppendChild(ele1);//添加到二级节点
XElement ele2=doc.CreateElement("Ele2");
ele2.SetAttribute("attribute","attr1");
ele2.SetAttribute("attribute","attr2");
ele2.InnerText="Comment";
node.AppendChild(ele2);//添加到二级节点
root.AppendChild(node);//添加到根节点
doc.Save("tmp.xml"); - 读取XML文件
C#中创建和读取XML文件
最新推荐文章于 2025-05-21 16:13:26 发布