Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get XML Elements from XmlDocument object?

Assume that an XmlDocument is successfully loaded with this code:

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

This is a sample portion of the XML stream (the complete XML stream has about 10000 of ProductTable's):

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

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

like image 693
user763554 Avatar asked Dec 25 '11 22:12

user763554


1 Answers

I suggest using an XDocument instead of an XmlDocument (the latter is not suited 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'd prefer to use sugar-coated SQL like syntax or would like to read up on the topic, this MSDN article is a great place to start.

The following is a more concise version if you feel like using 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 could then use this expressive syntax to print the 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();
like image 72
Adam Avatar answered Sep 19 '22 14:09

Adam