【问题标题】:Select all nodes with attribute using xpath使用 xpath 选择具有属性的所有节点
【发布时间】:2014-06-11 08:29:46
【问题描述】:

我正在尝试使用root.SelectNodes()XPath 选择所有节点。如需参考,请参阅msdn-documentation

following文档解释中,也可以搜索包含属性的节点(如果这确实是理解错误,请指正)。

所以我使用了下面这行代码:

XmlNodeList nodes = projectDoc.DocumentElement.SelectNodes("descendant::Compile[attribute::Include]");

我正在尝试读取以下数据:

<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
    <ItemGroup>
        <Compile Include="ArrayExtensions.cs" />
        <Compile Include="ArrayIterator.cs" />
        <Compile Include="AutoInitializeAttribute.cs" />
        <Compile Include="AutoInitializePriority.cs" />
        <Compile Include="AutoRegisterAttribute.cs" />
        <Compile Include="FormattableExtensions.cs" />
        <Compile Include="Mathematics\PrimeNumbers.cs" />
    </ItemGroup>
</Project>

如上面的代码示例所示,我想获取所有包含包含属性的 XmlNode。但是,当我执行我的代码时,nodes 包含 0 个元素。

我在这里做错了什么?

【问题讨论】:

  • 我强烈怀疑问题出在命名空间上——您实际上应该在 http://schemas.microsoft.com/developer/msbuild/2003 命名空间中寻找 Compile 元素。您是否有任何理由需要在 XPath 中执行此操作?使用 LINQ to XML,这将是微不足道的。
  • 没有特别的原因,如果您有更好的解决方案,将不胜感激!另外,我提供的问题的解决方案也很棒,仅用于学习目的。

标签: c# xml xpath


【解决方案1】:

我怀疑它失败的原因与属性部分无关 - 它根本找不到元素,因为你只要求 Compile 元素,而实际上只有 Compile 元素在具有 URI http://schemas.microsoft.com/developer/msbuild/2003 的命名空间。

使用 XPath 执行此操作可能需要使用 XmlNamespaceManager,然后将其传递给 another overload of SelectNodes。不过,我个人会使用 LINQ to XML:

XDocument doc = XDocument.Load("myfile.xml");
XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";
var elements = doc.Descendants(ns + "Compile")
                  .Where(x => x.Attribute("Include") != null);

总的来说,我发现 LINQ to XML 比“旧”的基于XmlDocument 的 API更加更干净。

【讨论】:

  • 我如何使用 Count 呢?我在 XDocument-API 中没有看到任何 XNodeList(或类似的)。我想说的是,这会返回什么?元素列表还是?
  • @Matthijs:它返回一个IEnumerable&lt;XElement&gt;。您可以像使用任何其他序列一样使用Count() 扩展方法。如果您想要List&lt;XElement&gt;,只需添加对.ToList() 的调用即可。
猜你喜欢
  • 2011-01-30
  • 1970-01-01
  • 1970-01-01
  • 2013-11-30
  • 1970-01-01
  • 2012-02-20
  • 1970-01-01
  • 1970-01-01
  • 2015-04-10
相关资源
最近更新 更多