1

I'm working on a .Net application for which I need to fetch values from a XML file based on the value of its sibling node's value.Eg: Here in the XML I want to fetch the values in Pages, Price & Author based on the title "Hansel and Gretel".

<?xml version="1.0" encoding="utf-8"?>
<Books>
  <Book>
    <Title>Hansel and Gretel</Title>
    <Pages>221</Pages>
    <Price>3.5</Price>
    <Author>Grimm</Author>
  </Book>
  <Book>
    <Title>Green Eggs and Ham</Title>
    <Pages>145</Pages>
    <Price>5.25</Price>
    <Author>Dr. Seuss</Author>
  </Book>
</Books>
Tim Smith
  • 72
  • 7

1 Answers1

1

Rather than searching for siblings, you can search for all parent elements <Book> with a conditional clause filtering for those with a certain value for their <Title> child element. Then, for all matches, return the values of the three desired child elements.

This can most easily be done using LINQ to XML:

var root = XElement.Parse(xmlString);

var title = "Hansel and Gretel";

var query = root
    .Elements("Book")
    .Where(e => (string)e.Element("Title") == title)
    .Select(e => new 
            {
                Pages = (int)e.Element("Pages"),
                Price = (decimal)e.Element("Price"),
                Author = (string)e.Element("Author"),
            });

var results = query.ToList();

However, if you prefer using XPath queries, you could do:

var query = root
    .XPathSelectElements(string.Format("/Book[Title='{0}']", title))
    .Select(e => new 
            {
                Pages = (int)e.Element("Pages"),
                Price = (decimal)e.Element("Price"),
                Author = (string)e.Element("Author"),
            });

Demo fiddle here.

dbc
  • 104,963
  • 20
  • 228
  • 340
  • What is the difference between LINQ to Xml and XPath? Why somebody will prefer to use XPath over LINQ? – Fabio Mar 10 '19 at 05:06
  • @Fabio -[tag:linq-to-xml] is a Microsoft API that provides a way to load XML into memory as a document object model which allows for easy querying using LINQ uniform functional query syntax. [tag:xpath] is a platform-independent textual query language for XML. Microsoft supports XPath for LINQ to XML objects via [`Extensions.XPathSelectElements`](https://learn.microsoft.com/en-us/dotnet/api/system.xml.xpath.extensions.xpathselectelements?view=netframework-4.7.2) If you are more familiar with LINQ, use LINQ. If you are more familiar with XPath, use that. – dbc Mar 10 '19 at 05:13
  • Sorry, but I was sure that `System.Xml.Linq;` is part of .NET Standard, which should be available on any platform. – Fabio Mar 10 '19 at 05:26