且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用XPath查询节点时如何指定名称空间?

更新时间:2023-11-17 12:22:40

在MSDN上得到回答:

This is answered on MSDN:

更新:

但是,请注意,在第二个示例XML中,当XPath查询时,< row> < cell> 元素不在XPath查询的名称空间中.将 xmlns:peanut 添加到 SelectionNamespaces 属性.这就是为什么未找到< cell> 元素的原因.

Note, however, that in your second example XML, the <row> and <cell> elements are NOT in the namespace being queried by the XPath when adding xmlns:peanut to the SelectionNamespaces property. That is why the <cell> elements are not being found.

要将它们正确放置到名称空间中,您必须:

To put them into the namespace properly, you would have to either:

  • 将名称空间声明更改为使用 xmlns = 而不是 xmlns:ss = :

<row xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <cell>a</cell>
    <cell>b</cell>
    <cell>c</cell>
</row>

  • 使用< ss:row> < ss:cell> 而不是< row> < cell> :

    <ss:row xmlns:ss="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
        <ss:cell>a</cell>
        <ss:cell>b</cell>
        <ss:cell>c</cell>
    </ss:row>
    

  • SelectionNamespaces 属性不会为您神奇地将元素放入命名空间,它仅指定XPath查询可以使用哪些命名空间.XML本身必须根据需要将元素放入适当的名称空间中.

    The SelectionNamespaces property does not magically put elements into a namespace for you, it only specifies which namespaces are available for the XPath query to use. The XML itself has to put elements into the proper namespaces as needed.

    更新:

    在新示例中, cells:= row.selectNodes('/ss:row/ss:cell'); 不起作用,因为XPath查询使用的是绝对值路径,其中前导/从文档根开始,并且XML文档顶部没有< row> 元素,只有< worksheet> 元素.这就是 rows:= doc.selectNodes('/ss:worksheet/ss:row'); 起作用的原因.

    In your new example, cells := row.selectNodes('/ss:row/ss:cell'); does not work because the XPath query is using an absolute path, where the leading / starts at the document root, and there are no <row> elements at the top of the XML document, only a <worksheet> element. That is why rows := doc.selectNodes('/ss:worksheet/ss:row'); works.

    如果要执行从要查询的节点开始的XPath查询,请不要使用绝对路径,而应使用相对路径:

    If you want to perform an XPath query that begins at the node being queried, don't use an absolute path, use a relative path instead:

    cells := row.selectNodes('ss:row/ss:cell');
    

    或者简单地:

    cells := row.selectNodes('ss:cell');