How to get XML elements from an XmlDocument object?

Suppose the XmlDocument is loaded successfully with this code:

var doc = new XmlDocument(); doc.Load(stream); 

This is an example part of an XML stream (a full XML stream has about 10,000 ProductTable products):

 <ProductTable> <ProductName>Chair</ProductName> <Price>29.5</Price> </ProductTable> 

Using Linq, how do I access the ProductName and Price elements? Thanks.

+4
source share
1 answer

I suggest using XDocument instead of XmlDocument (the latter is not suitable for LINQ to XML). Use the XDocument.Load(...) method to load your "real" XML.

 string xml = @"<ProductTable> <ProductName>Chair</ProductName> <Price>29.5</Price> </ProductTable>"; XDocument x = XDocument.Parse(xml); var tables = x.Descendants("ProductTable"); Dictionary<string,string> products = new Dictionary<string, string>(); foreach (var productTable in tables) { string name = productTable.Element("ProductName").Value; string price = productTable.Element("Price").Value; products.Add(name, price); } 

If you prefer to use SQL-like syntax with sugar or want to read it, this MSDN article is a great place to start.

Below is a more succinct option if you like to use an anonymous type :

 XDocument document = XDocument.Parse(xml) var products = /* products is an IEnumerable<AnonymousType> */ from item in document.Descendants("ProductTable") select new { Name = item.Element("ProductName").Value, Price = item.Element("Price").Value }; 

You can then use this expressive syntax to print matches in the console:

 foreach (var product in products) /* var because product is an anonymous type */ { Console.WriteLine("{0}: {1}", product.Name, product.Price); } Console.ReadLine(); 
+8
source

Source: https://habr.com/ru/post/1387965/


All Articles