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文件
首先要加上引用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文件提取字符串+字符串存为XML文件+创建XML(自定义节点)文件+读取节点内容
- 在C#中创建和读取XML文件
- 在C#中创建和读取XML文件
- 在C#中创建和读取XML文件的实现方法
- 一个经过改良的XMLHelper(包含了序列化,反序列化,创建xml文件,读取节点,C#对象与xml文件的相互转换等等。)
- 在C#中创建和读取XML文件
- C# 创建 读取 更新 XML文件
- c# 创建、读取、添加、修改xml文件
- c# 创建、读取、添加、修改xml文件
- 在C#中创建和读取XML文件
- C# 创建 读取 更新 XML文件
- C#使用GDAL读取与创建影像
- C#使用Linq操作Xml文件(创建xml文件、增删改查xml文件节点信息)的方法
- c#配置文件INI的创建、写入与读取
- (转)使用XmlTextWriter与XmlTextReader访问创建和读取XML文件
- C#中常用的几种读取XML文件的方法
- C#读取和创建注册表的某一项
- 用C#实现XML文件的读取
- C#中创建、打开、读取、写入、保存Excel的一般性代码[转]
- c#读取xml文件