1
<?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.

Macy Abbey
  • 3,877
  • 1
  • 20
  • 30
Gerry Jones
  • 11
  • 1
  • 2

2 Answers2

3

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();
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
1

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
               });
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
  • I tried to formulate a pure XPath solution but it is more complicated than necessary. These any of these approaches (including BrokenGlass') should work fine for you. – Jeff Mercado Jan 27 '11 at 05:38
  • M: You wrote *"I tried to formulate a pure XPath solution but it is more complicated than necessary"* There is no pure XPath solution because XPath has no variable binding operator. +1 For XPath approuch. –  Jan 27 '11 at 17:57