XmlDocument GetElementsByTagName within a specified block in C#

23,169

Solution 1

You are not using Linq to XML:

var doc = XDocument.Load("data.xml");

var bookNodes = doc.Descendants("book").Where(b=> b.Parent.Name == "shop");

using regular System.Xml:

var doc = new XmlDocument();
doc.Load("data.xml");
var bookNodes = doc.SelectNodes(@"//bookstore/book");
foreach (XmlNode item in bookNodes)
{
    string title = item.SelectSingleNode("./title").InnerText;
    string price = item.SelectSingleNode("./price").InnerText;
    Console.WriteLine("title {0} price: {1}",title,price); //just for demo
}

Solution 2

You can use XDocument class following way:

XDocument Doc = XDocument.Load("data.xml");
// getting child elements of bookstore
var result = from d in Doc.Descendants("bookstore").Descendants("book")
             select new 
             {
               Name = d.Element("title").Value,
               Price = d.Element("price").Value
             };

// getting child elements of shop
var result = from d in Doc.Descendants("shop").Descendants("book")
             select new 
             {
               Name = d.Element("title").Value,
               Price = d.Element("price").Value
             };
Share:
23,169
Doro
Author by

Doro

I am a software Engineer, working mostly with Microsoft Technologies (C#, .NET, SQL Server, ADO.NET/EF). But, also a lover of C/C++, Java, R, and SQLite.

Updated on February 19, 2020

Comments

  • Doro
    Doro about 4 years

    I have an xml file and currently I am getting element-by-tag-name. What I am trying to achieve is to specify which block to use, such as bookstore or shop. Thank you for any help and advice.

    XML:

    <VariablesSpecs name="Data01">
      <bookstore>
        <book genre='novel' ISBN='10-861003-324'>
          <title>The Handmaid's Tale</title>
          <price>19.95</price>
        </book>
      </bookstore>
      <shop>
        <book genre='novel' ISBN='10-861003-324'>
          <title>The Handmaid's Tale</title>
          <price>19.95</price>
        </book>
      </shop>
    </VariablesSpecs>
    

    Code:

    var doc = new XmlDocument();
    doc.Load("data.xml");
    
    var bookNodes = doc.GetElementsByTagName("book");
    foreach (var bookNode in bookNodes)
    {
        // Collect data.
    }
    
  • Doro
    Doro about 9 years
    I know but would be nice also to have smt with LinqToXml. But, what about smt without linq?
  • Doro
    Doro about 9 years
    Thank you, and without linq using XmlDocument?
  • Doro
    Doro about 9 years
    How can i implement with the foreach loop?
  • Ehsan Sajjad
    Ehsan Sajjad about 9 years
    i always prefer to use XDocument because it is easy to traverse the document
  • Florian Schmidinger
    Florian Schmidinger about 9 years
    @doro if you also need attributes: string isbn = item.Attributes.GetNamedItem("ISBN").Value; string isbnusingxpath = item.SelectSingleNode("./@ISBN").InnerText;