config.xml文件如下:
<?xml version="1.0" encoding="gb2312" ?> <root> <person name="WangYao"> <age>25</age> </person> <person name="Jobs"> <age>56</age> </person> </root>
C#解析代码如下:
XmlDocument doc = new XmlDocument(); doc.Load("config.xml"); //加载Xml文件 XmlElement rootElem = doc.DocumentElement; //获取根节点 XmlNodeList personNodes = rootElem.GetElementsByTagName("person"); //获取person子节点集合 foreach (XmlNode node in personNodes) { string strName = ((XmlElement)node).GetAttribute("name"); //获取name属性值 Console.WriteLine(strName); XmlNodeList subAgeNodes = ((XmlElement)node).GetElementsByTagName("age"); //获取age子XmlElement集合 if (subAgeNodes.Count == 1) { string strAge = subAgeNodes[0].InnerText; Console.WriteLine(strAge); } } Console.ReadLine();