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

时间:2015-05-15 00:10:23

标签: c# xml linq linq-to-xml

我有以下xml:

{{1}}

我需要查找具有特定cat_id的所有行。 LINQ查询将如何?我试过了

{{1}}

但它什么也没有返回。

2 个答案:

答案 0 :(得分:3)

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

如果您阅读documentation,您会知道Element()方法返回第一个匹配元素,在这种情况下,返回<col name="id">1</col>行。由于该属性名为&#34; name&#34;在第一个匹配元素中没有&#34; cat_id&#34;的值,它会移动到下一个row元素。

如果&#34; cat_id&#34;您的查询可以正常工作确保每次都是第一个匹配元素。

如果您无法确定或无法进行更改,首先需要搜索名为&#34; cat_id&#34;的所有属性,然后查找一个具有特定价值的人。

首先,要获取所有子元素,您需要使用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.

答案 1 :(得分:0)

假设root是你的XElement“表”你的where子句选择每个“行”中的第一个XElement“col”。 for“col”元素的属性是“id”,它永远不会等于“cat_id”。

你想要做的是:

XDocument xmlDoc = XDocument.Load("test.xml");
XElement root = xmlDoc.Element("table");
Dictionary<string, List<XElement>> s1 = root.Elements("row")
                                            .GroupBy(ks => ks.Elements("col").Single(p => p.Attribute("name").Value == "cat_id").Value)
                                            .ToDictionary(ks => ks.Key, es => es.ToList());

它为您提供了一个字典,其中cat_ids为键,每个键的XElement行列表

在这个例子中,我没有考虑没有name属性的cols和缺少cat_id的行 - 这将为你提供在查询表达式中需要处理的NullReferenceException