【问题标题】:Trying to select elements by child element尝试按子元素选择元素
【发布时间】:2014-10-04 15:26:24
【问题描述】:

我正在使用 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 作为 lambda 或普通 LINQ 查询检索每个类别标题为“Finance”的项目?

我有这个不起作用的 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);

【问题讨论】:

  • 不幸的是,这仍然不起作用。
  • 名字?而是标题。等一下,我正在努力。

标签: .net xml linq


【解决方案1】:

简单的 XPath 解决方案将是

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

或者,

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

【讨论】:

    【解决方案2】:

    效果很好:

            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

    【讨论】:

      【解决方案3】:

      我相信这应该为你做到这一点

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

      【讨论】:

        猜你喜欢
        • 2013-05-18
        • 1970-01-01
        • 1970-01-01
        • 2023-01-26
        • 2013-02-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多