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");
XmlNode xmlRoot = xmlDocument.SelectSingleNode("Root");
XmlNode xmlChild1 = xmlRoot.SelectSingleNode("Child1");
XmlNode xmlChild2 = xmlRoot.SelectSingleNode("Child2");
Console.WriteLine("xmlChild2.InnerText is:" + xmlChild2.InnerText);
XmlNode xmlChild3 = xmlRoot.SelectSingleNode("Child3");
XmlNode xmlChild3Child = xmlChild3.SelectSingleNode("Child3的XmlElementInner");
foreach (XmlAttribute value in xmlChild3Child.Attributes)
{
Console.WriteLine(value.Name + " " + value.Value);
}
Console.WriteLine("xmlChild3Child.InnerText is:" + xmlChild3Child.Attributes.GetNamedItem("我是键").Value);
<?xml version="1.0" encoding="UTF-8"?> <Root> <Child1 /> <Child2>我是Child2的值呀</Child2> <Child3> <Child3的XmlElementInner 我是键="我是值" 我是键1="我是值1" /> </Child3> </Root>