我有以下 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/