Tim Smith
Tim Smith

Reputation: 72

How to fetch XML node based on value of sibling node?

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>

Upvotes: 1

Views: 476

Answers (1)

dbc
dbc

Reputation: 117105

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.

Upvotes: 1

Related Questions