Skip to main content
 首页 » 编程设计

c#之如果子节点满足特定条件,则检索 XML 父节点属性并将两者分配给变量

2024年02月23日16lori

<?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 (递增变量)。

所以,最终结果应该返回..

x1 = 501 y1 = 汽车

x2 = 750 y2 = 房子

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

请您参考如下方法:

LINQ to XML来救援!

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