c# - 在 XPather.com 上使用 XML 命名空间的奇怪 XPath 行为?

标签 c# xml xpath xml-namespaces

我有以下 XML:

<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
          xmlns:o="urn:schemas-microsoft-com:office:office"
          xmlns:x="urn:schemas-microsoft-com:office:excel"
          xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
          xmlns:html="http://www.w3.org/TR/REC-html40">
  <Names>
    <NamedRange ss:Name="SomeNamedRange" ss:RefersTo="=Control!R1C1:R51C4"/>
  </Names>
  <Worksheet ss:Name="Control" ss:Protected="1">
    <Table ss:ExpandedColumnCount="4" ss:ExpandedRowCount="51">
      <Row>
        <Cell ss:StyleID="s145">          
          <Comment ss:Author="Some comment here">
            <ss:Data xmlns="http://www.w3.org/TR/REC-html40"></ss:Data>
          </Comment>          
        </Cell>
      </Row>      
    </Table>
  </Worksheet>
</Workbook>

我想使用 XPath 获取 Names 元素,所以我尝试:

//Names

但这不起作用。到目前为止,我已经找到了很多方法来解决这个问题。

//ss:Names
//*:Names
//*[local-name()='Names']

或者,我可以删除以下元素:

<ss:Data xmlns="http://www.w3.org/TR/REC-html40"></ss:Data>

很明显,这与命名空间有关,但我仍然不太明白发生了什么。所以我有两个问题:

  1. 为什么删除 ss:Data 元素会影响读取 Names 元素?
  2. 鉴于顶部声明了 5 个命名空间,为什么 Names 元素被视为位于 ss 命名空间中(当 ss:Data 元素存在)?
  3. 这里正确的一般方法是什么?我觉得我缺少一些关于 XML 或 XPath 的一般信息

编辑:

此问题不限于http://xpather.com/ 。我在不同的 XPath 网站上得到了各种结果,并总结了结果 here .

最佳答案

您感到困惑是对的。

仅删除 ss:Data 不会导致 //Names 突然选择 WorkbookNames 子项当 Workbook 声明默认命名空间 urn:schemas-microsoft-com:office:spreadsheet 时。您似乎在 xpather.com 中偶然发现了一个错误。请注意,它们的开放默认 XML 具有以下有关 namespace 的免责声明:

This application is in an early beta version so please be forgiving. XPath 2.0 is supported but namespaces are still being added and they may not fully work yet. Please send your comments to: [email protected]

另请参阅(有关命名空间中的一般 XPath 指南):


另一个 xpather.com 问题

目前,xpather.com不明白元素名称可能包含句点 (.) 字符。


还有另一个 xpather.com 问题

这个完全兼容的 XPath,

//item/comment()[not(preceding-sibling::*)]

导致 xpather.com 上出现以下(不正确的)错误消息:

TypeError: Cannot read property 'childPosition' of undefined

关于c# - 在 XPather.com 上使用 XML 命名空间的奇怪 XPath 行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59212433/

相关文章:

xml - 使用 XPath 获取属性并使用 value 属性提供内部文本

xslt - 如何匹配XSLT中的处理指令元素?

c# - 自定义事件多次触发

c# - 处理双工 WCF 服务中的客户端断开连接

java - 想要在 XML 文件中遇到特殊的 UTF-8 字符时抛出异常

xml - BeautifulSoup 抑制 lxml 解析错误?

python - 提取属性值,Lxml

c# - 如何绘制没有边缘的图像

c# - Entity Framework 6 代码优先触发器

java - 克隆 dom.Document 对象