您的位置:首页 > 编程语言 > C#

C#中创建和读取XML文件

2013-03-18 17:06 218 查看
创建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文件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: