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

标签 c# xml linq linq-to-xml

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

相关文章:

c# - 类型比较未返回预期结果

.net - .NET 中的速度和 XML 解析 - 序列化与 XML DOM 比较?

php simpleXMLElement 到数组 : null value

c# - 在 C# 中使用 Linq 匹配 2 个集合之间的元素

.net - 如何将 System.Data.Linq.Binary 转换为流?

c# - 如果两个字符串都包含值,则需要连接两个字符串;如果第一个字符串为 NULL,则返回一个值

c# - MVC ASP.NET 正在使用大量内存

c# - 在 EF CF 中建模有向图

c# - 如何解析没有定义结构的 JSON.NET 文件?

java - 使用 Jackson 数据格式 XML 将 XML 转换为 Java 对象