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 = 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) { Console.WriteLine("{0}: {1}", product.Name, product.Price); } Console.ReadLine();
source share