<?xml version="1.0" encoding="utf-8" ?> <Computers> <Computer id="001"> <Name>呵呵</Name> <Price>300</Price> <Cpu>aa</Cpu> </Computer> <Computer id="002"> <Name>嘿嘿</Name> <Price>500</Price> <Cpu>aaaaaa</Cpu> </Computer> </Computers>
1.一个循环
#region 一个循环 //解析xml找一个工具 一个类XmlDocument //1.1 在Cache中构建一个新的文档对象 XmlDocument doc = new XmlDocument(); //1.2用Load渲染数据 doc对象 doc.Load("XMLFile1.xml"); //1.3属性DocumentElement; XmlNode root = doc.DocumentElement; foreach (XmlNode item in root.ChildNodes) { string id = item.Attributes["id"].Value; Console.WriteLine("编号;"+id); Console.WriteLine("名称:"+item["Name"].InnerText); Console.WriteLine("价格:" + item["Price"].InnerText); Console.WriteLine("CPU:" + item["Cpu"].InnerText); } #endregion
2.两个循环
#region 两个循环 //解析xml找一个工具 一个类XmlDocument //1.1 在Cache中构建一个新的文档对象 XmlDocument doc = new XmlDocument(); //1.2用Load渲染数据 doc对象 doc.Load("XMLFile1.xml"); //1.3属性DocumentElement; XmlNode root = doc.DocumentElement; foreach (XmlNode item in root.ChildNodes) { foreach (XmlNode Child in item.ChildNodes) { switch (Child.Name) { case "Name": Console.WriteLine("名称:" + Child.InnerText); break; case "Price": Console.WriteLine("价格:" + Child.InnerText); break; case "Cpu": Console.WriteLine("CPU:" + Child.InnerText); break; } } } #endregion