简体   繁体   English

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

[英]Select all nodes with attribute using xpath

I am trying to select all nodes using root.SelectNodes() with XPath . 我试图选择将root.SelectNodes()XPath一起使用的所有节点。 For reference, see msdn-documentation . 有关参考,请参见msdn-documentation

In the following document explained, you can also search for nodes that contain attributes (correct me if this is actually a wrong understanding). 下面解释的文档中,您也可以搜索包含属性的节点(如果这实际上是错误的理解,请纠正我)。

So I used the following line of code: 因此,我使用了以下代码行:

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

And I am trying to read the following data: 我正在尝试读取以下数据:

<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>

As shown in the code-sample above, I want to get all the XmlNodes that contain the Include-attribute. 如上面的代码示例所示,我想获取所有包含Include-attribute的XmlNodes。 However, when I execute my code, nodes contains 0 elements. 但是,当我执行代码时, nodes包含0个元素。

What am I doing wrong here? 我在这里做错了什么?

I suspect the reason it's failing has nothing to do with the attribute part - it's failing to find the elements at all, as you've asked for just Compile elements, whereas there are only actually Compile elements in the namespace with the URI http://schemas.microsoft.com/developer/msbuild/2003 . 我怀疑它失败的原因与属性部分无关-它根本找不到元素,因为您只要求Compile元素,而实际上在URI http://schemas.microsoft.com/developer/msbuild/2003的名称空间中实际上只有Compile元素http://schemas.microsoft.com/developer/msbuild/2003

Doing this with XPath probably requires the use of an XmlNamespaceManager which you'd then pass into another overload of SelectNodes . 使用XPath进行此操作可能需要使用XmlNamespaceManager ,然后将其传递给另一个SelectNodes重载 Personally I would use LINQ to XML instead though: 我个人将使用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);

In general, I find LINQ to XML to be a much cleaner API than the "old" XmlDocument -based API. 在一般情况下,我找到的LINQ to XML比“老” 清洁 API XmlDocument为基础的API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM