简体   繁体   中英

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.

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();

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
               });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM