如果子节点满足特定条件,则检索 XML 父节点属性并将两者分配给变量 [英] Retrieve XML parent node attribute if child node meets a certain criteria and assign both to variables

查看:26
本文介绍了如果子节点满足特定条件,则检索 XML 父节点属性并将两者分配给变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

============

===========

我想要做的是搜索具有 500 或更多值的成本"的节点,如果是这种情况,获取项目"描述并将描述分配给变量 x1 并将成本分配给 y1(增加变量).

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 = 501y1 = 汽车

x1 = 501 y1 = car

x2 = 750y2 = 房子

x2 = 750 y2 = house

如果可能,我想使用 Xpath 或类似工具在 C# 中维护它.

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

推荐答案

LINQ toXML 来救援!

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

这篇关于如果子节点满足特定条件,则检索 XML 父节点属性并将两者分配给变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆