gpt4 book ai didi

c# - LINQ to XML 查找xml中的特定类别

转载 作者:行者123 更新时间:2023-11-30 21:58:12 26 4
gpt4 key购买 nike

我有以下 xml:

<table name="transactions">
<row>
<col name="id">1</col>
<col name="amount">2673.9</col>
<col name="created_date">2014-10-19</col>
<col name="display_date">2014-04-22</col>
<col name="cat_id">13</col>
<col name="note">Initial Balance</col>
//other col tags
</row>
<row>
...
</row>
</table>

我需要找到具有特定 cat_id 的所有行。 LINQ 查询会是什么样子?我试过了

IEnumerable<XElement> rows = 
from el in root.Elements("row")
where (string)el.Element("col").Attribute("name") == "cat_id"
select el;

但它什么也没返回。

最佳答案

首先,您需要了解如何编写 LINQ 查询。

如果您阅读 documentation , 你会知道 Element()方法返回第一个匹配元素,在本例中为 <col name="id">1</col>行被返回。由于第一个匹配元素中名为“name”的属性没有值“cat_id”,因此它移至下一个 row。元素。

如果每次都确保“cat_id”是第一个匹配元素,您的查询就可以工作。

如果您不能确定或无法进行更改,您首先需要在所有 属性中搜索名为“cat_id”的属性,然后查找具有特定值的属性。

首先,要获取所有子元素,您需要使用 Elements() 方法代替。然后您需要查找特定的属性名称和值。

IEnumerable<XElement> rows = from el in xdocument.Root.Elements("row")
from col in el.Elements("col")
where (string)col.Attribute("name") == "cat_id"
where col.Value =="13"
select el;

此查询将返回所有具有 col 的行具有名为 name 的属性的元素值 cat_id .然后仅当具有 cat_id 属性的元素的值为 13 时。

关于c# - LINQ to XML 查找xml中的特定类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30249489/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com