【问题标题】:What is the LINQ to XML equivalent for this XPath此 XPath 的 LINQ to XML 等效项是什么
【发布时间】:2009-01-15 22:27:28
【问题描述】:

我想知道用 LINQ 实现这个 xpath 查询的“最佳实践”方式(在 C# 中)是什么:

/topNode/middleNode[@filteringAttribute='filterValue']/penultimateNode[@anotherFilterAttribute='somethingElse']/nodesIWantReturned

我想要一个“nodesIWantReturned”的 IEnumerable 列表,但只能来自 XML 树的某个部分,具体取决于祖先属性的值。

【问题讨论】:

标签: c# xml linq xpath


【解决方案1】:

除了所示的 Linq 方法之外,您还可以导入 System.Xml.XPath 命名空间,然后使用 XPathSelectElements 扩展方法直接使用您的 XPath 查询。

在课堂上注意到这些方法比“正确的”Linq-to-XML 慢,但是很多时候这并不是很重要,有时使用 XPath 会更容易(当然很多更简洁!)。

var result = doc.XPathSelectElements("your xpath here");

【讨论】:

  • 谢谢!很棒的提示!会注意到这比较慢。
【解决方案2】:
var result = root.Elements("topNode")
                 .Elements("middleNode")
                 .Where(a => (string)a.Attribute("filteringAttribute") == "filterValue")
                 .Elements("penultimateNode")
                 .Where(a => (string)a.Attribute("anotherFilterAttribute") == "somethingElse")
                 .Elements("nodesIWantReturned");

【讨论】:

  • 在前三个节点选择中使用 .Elements 而不是 .Descendants 不是更安全吗? . 如果nodesIWantReturned 的内容匹配,后代可能会到达太远?
  • 嗯,是的。谢谢。看来我困了 :) 编辑
【解决方案3】:

一个更口头的解决方案:

var nodesIWantReturned = from m in doc.Elements("topNode").Elements("middleNode")
              from p in m.Elements("penultimateNode")
              from n in p.Elements("nodesIWantReturned")
              where m.Attribute("filteringAttribute").Value == "filterValue"
              where p.Attribute("anotherFilterAttribute").Value == "somethingElse"
              select n;

【讨论】:

  • 这将无法正常工作。如果遇到缺少该属性的元素,它将抛出 NullReferenceException。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-10
  • 2017-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多