试图按子元素选择元素

时间:2014-10-04 15:26:24

标签: .net xml linq

我正在使用Visual Studio 2013,C#...

我在变量'myXml'中有这个XML:

<root>
<article><title>A1</title><category><title>Geography</title></category></article>
<article><title>A2</title><category><title>History</title></category></article>
<article><title>A3</title><category><title>Geography</title></category></article>
<article><title>A4</title><category><title>Finance</title></category></article>
</root>

如何使用LINQ2XML检索具有类别标题“Finance”的每个,作为lambda或普通LINQ查询?

我有这个LINQ查询不起作用:

var doc = XDocument.Parse(myXml);

var l = (from d in doc.Elements("root").Elements("article")
                    where d.Elements("category").Elements("title").Equals("Finance")
                    select d);

3 个答案:

答案 0 :(得分:1)

简单的XPath解决方案将是

 var l = doc.XPathSelectElements("/root/article[category/title/text() = \"Finance\"]");

Alernatively,

var l = (from d in elem.Element("root")
            .Elements("article")
            .Elements("category")
            .Elements("title")
            .Where(x => x.Value == "Finance")
            select d.Parent.Parent);

答案 1 :(得分:0)

我相信这应该为你做到

 var l = from att in XDocument.Parse(myXml)
                .Element("root")
                .Elements("article")
                .Elements("category")
                .Where(x => x.Value == "Finance")
                select att;

答案 2 :(得分:0)

它工作正常:

        var query = from article in doc.Descendants("article")
                    where ((string)article.Element("category").Element("title").Value == "Finance")
                    select article;

方法Equals不能用于通过参数与其他对象进行比较。请看这里: Distinct not working with LINQ to Objects