【问题标题】:Select unique XElements (by attribute) using LinqToXml使用 LinqToXml 选择唯一的 XElement(按属性)
【发布时间】:2012-09-11 07:55:30
【问题描述】:

我有一个 XML,其中有几个 <testcase> 标签。其中一些具有属性“ident”,其值为“pr”,而另一些则没有。

<testcase>
  <teststep ident="Preparation" result="na">blabla</teststep>
  <teststep ident="" result="pass">blabla</teststep>
  <teststep ident="-" result="na">blabla</teststep>
  <teststep ident="Info" result="na">blabla</teststep>
  <teststep ident="1" result="pass">blabla</teststep>
  <teststep ident="2" result="pass">blabla</teststep>
  <teststep ident="3" result="pass">blabla</teststep>
  <teststep ident="4" result="fail">blabla</teststep>
  <teststep ident="PR" result="na">blabla</teststep>
  <verdict result="fail" />
</testcase>

我想查询包含 ident 属性值为“pr”的测试用例

IEnumerable<XElement> failedPRTCs = report.Descendants("testcase").Where(t => t.Element("verdict").Attribute("result").Value == "fail" && t.Descendants("teststep").Where(ts=> ts.Attribute("ident").Value == "pr").ToList().Count > 0).ToList();

当前查询返回 0。有什么问题?

【问题讨论】:

    标签: xml linq-to-xml xelement xattribute


    【解决方案1】:

    看起来像一个简单的套管问题! "pr""PR"!我还建议使用Any 而不是count &gt; 0

    IEnumerable<XElement> failedPRTCs = report.Descendants("testcase")
        .Where(t => t.Element("verdict").Attribute("result").Value == "fail" &&
               t.Descendants("teststep").Any(ts=> ts.Attribute("ident").Value == "PR"));
    

    【讨论】:

    • 是的,谢谢 :) 我确实犯了一个简单的错误.. 小写的“pr”而不是“PR”。并感谢有关 Any 关键字的建议
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多