使用xpath选择具有属性的所有节点

时间:2014-06-11 08:29:47

标签: c# xml xpath

我正在尝试使用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>

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

我在这里做错了什么?

1 个答案:

答案 0 :(得分: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是一个很多更干净的API而不是&#34; old&#34;基于XmlDocument的API。