C# 读写XML文件的方法

一.写XML文件

     
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.AppendChild(xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", null));
XmlElement xmlRoot = xmlDocument.CreateElement("Root");
xmlDocument.AppendChild(xmlRoot);

XmlElement xmlChild = xmlDocument.CreateElement("Child1");
xmlRoot.AppendChild(xmlChild);

xmlChild = xmlDocument.CreateElement("Child2");
xmlChild.InnerText = "我是Child2的值呀";
xmlRoot.AppendChild(xmlChild);

xmlChild = xmlDocument.CreateElement("Child3");
XmlElement xmlElementInner = xmlDocument.CreateElement("Child3的XmlElementInner");
XmlAttribute xmlAttribute = xmlDocument.CreateAttribute("我是键");
xmlAttribute.Value = "我是值";
xmlElementInner.Attributes.SetNamedItem(xmlAttribute);
xmlChild.AppendChild(xmlElementInner);

xmlRoot.AppendChild(xmlChild);
xmlDocument.Save("XMLConfig.xml");
 

二.读取XML文件

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load("XMLConfig.xml");

 

 

<?xml version="1.0" encoding="UTF-8"?>
<Root>
  <Child1 />
  <Child2>我是Child2的值呀</Child2>
  <Child3>
    <Child3的XmlElementInner 我是键="我是值" 我是键1="我是值1" />
  </Child3>
</Root>

 

        

相关文章: