Search code examples
c#xmllinq-to-xmlxmldocument

XmlDocument GetElementsByTagName within a specified block in C#


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.
}

Solution

  • 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
    }