Gerry Jones
Gerry Jones

Reputation: 11

Retrieve XML parent node attribute if child node meets a certain criteria and assign both to variables

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
<top>
   <item description="book">
      <cost>250</cost> 
   </item>
   <item description="car">
      <cost>501</cost> 
   </item>
   <item description="house">
      <cost>700</cost> 
   </item>
</top>

===========

What I want to do is search for nodes that have "cost" with a value of 500 or more and if that is the case, grab the "item" description and assign the description to variables x1 and the cost to y1 (incrementing the variables).

So, the end result should return..

x1 = 501 y1 = car

x2 = 750 y2 = house

If possible I would like to maintain this in C# using Xpath or similar.

Upvotes: 1

Views: 2658

Answers (2)

Jeff Mercado
Jeff Mercado

Reputation: 134801

Using LINQ to XML:

XDocument doc = ...;
var query = from e in doc.Descendants("item")
            let cost = Convert.ToInt32(e.Value)
            where cost >= 500
            select new 
            {
                x = cost,
                y = e.Attribute("description").Value
            };

Or in conjunction with an XPath:

XDocument doc = ...;
var query = doc.XPathSelectElements("/*/item[cost >= 500]")
               .Select(e => new
               {
                   x = Convert.ToInt32(e.Value),
                   y = e.Attribute("description").Value
               });

Upvotes: 1

BrokenGlass
BrokenGlass

Reputation: 160852

LINQ to XML to the rescue!

XDocument doc = XDocument.Load(@"test.xml");
var items = doc.Descendants("cost")
               .Where(c => Convert.ToInt32(c.Value) >= 500)
               .Select(c => new { x = c.Value, y = c.Parent.Attribute("description").Value })
               .ToList();

Upvotes: 3

Related Questions