使用c#解析XML数据

我一直在c#中使用XMLReaderClass挣扎一段时间,似乎无法得到这个概念。 基本上我想循环遍历XML文件,如果xml doc中的类别与我传递的类别相同,我想将其名称添加到List中。

这是xml

                  

这是我的代码,我已经开始工作,但没有得到很远:(

 public ReadOnlyCollection GetProductsByCategory(string category) { List returnList = new List(); using (XmlReader productsReader = GetProductsReader()) { productsReader.MoveToContent(); while (productsReader.Read()) if(productsReader.NodeType == XmlNodeType.Element) { if (productsReader) { if productsReader } } } return new ReadOnlyCollection(returnList); } 

在这里使用XmlReader将是一件痛苦的事情。 使用该API使用LINQ to XML,它将使您的生活更轻松。

 public static ReadOnlyCollection GetProductsByCategory(string category) { using (var reader = GetProductsReader()) { var doc = XDocument.Load(reader); var results = doc.Element("Products") .Elements("product") .Where(e => (string)e.Attribute("category") == category) .Select(e => (string)e.Attribute("name")) .ToList(); return new ReadOnlyCollection(results); } } 

如果由于某种原因你仍然希望使用XmlReader ,你可以这样读:

 public static ReadOnlyCollection GetProductsByCategory(string category) { var results = new List(); var settings = new XmlReaderSettings { IgnoreWhitespace = true, IgnoreComments = true, }; using (var reader = XmlReader.Create(GetProductsReader(), settings)) { reader.MoveToContent(); reader.ReadStartElement("Products"); do { if (reader.IsStartElement("product")) { if (reader.MoveToFirstAttribute()) { string currentCategory = null; string currentName = null; do { switch (reader.Name) { case "category": currentCategory = reader.ReadContentAsString(); break; case "name": currentName = reader.ReadContentAsString(); break; } } while (reader.MoveToNextAttribute()); if (currentCategory == category && currentName != null) results.Add(currentName); } } } while (reader.ReadToNextSibling("product")); } return new ReadOnlyCollection(results); } 

对于非常大的XML文件,使用XmlReader扫描文档比使用XmlDocumentXDocument更有效,这需要将整个文件加载到内存中。 访问XmlReader.LocalName属性以确定读取器所在元素的类型,并调用XmlReader.GetAttribute()方法以获取属性的值。

 public ReadOnlyCollection GetProductsByCategory(string category) { List products = new List(); using (XmlReader productsReader = GetProductsReader()) { productsReader.MoveToContent(); while (productsReader.Read()) { if (productsReader.NodeType == XmlNodeType.Element && productsReader.LocalName == "product" && productsReader.GetAttribute("category") == category) { products.Add(productsReader.GetAttribute("name")); } } } return new ReadOnlyCollection(products); } 

我会使用LINQ to XMl(XDocument)而不是旧读者。 这将使您开始(假设您的xml位于c:\ temp目录中的文件中):

  var doc = XDocument.Load(@"c:\temp\testxml.xml"); foreach(var element in doc.Elements("Products").Elements()) { Console.WriteLine(element.Attribute("category")); } 

查看Linq to XML,这是一个查找特定属性的示例

http://msdn.microsoft.com/en-us/library/bb387041.aspx