xslt - 相同的 xpath 在命令行上有效,但在 xslt 中无效

标签 xslt xpath xml-namespaces

我是 xslt 和 xpath 的初学者。在命令行(Ubuntu 14.04)上使用带有 xml 文件的 xpath 是可行的,但是 xslt 文件中的相同 xpath 什么也不返回。我正在使用瞻博网络 Junos xml 文件。有什么建议么?
谢谢,
乔治

xml 文件开头为:

<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:junos="http://xml.juniper.net/junos/12.3R8/junos">
  <interface-information xmlns="http://xml.juniper.net/junos/12.3R8/junos-interface" junos:style="normal">
    <physical-interface>
      <name>fe-0/1/0</name>
      <logical-interface>
        <name>fe-0/1/0.0</name>
          ...

在 Ubuntu 14.04 中工作的命令行是:xpath -e "/rpc-reply/interface-information/physical-interface/logical-interface/name" interfaces.xml
xslt 文件是:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
  version="2.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <html>
  <body>
    <h2>Interfaces</h2>
    <table border="1">
      <tr bgcolor="#9acd32">
        <th>Name</th>
      </tr>
      <xsl:for-each select="/rpc-reply/interface-information/physical-interface/logical-interface">
        <tr>
          <td><xsl:value-of select="name"/></td>
        </tr>
      </xsl:for-each>
    </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

最佳答案

这里的问题很简单。您没有在 XPath 中使用 namespace 。显然,您的命令行实用程序并不关心,或者基于元素的 QName 评估 XPath 会忽略默认命名空间,并且还会对命名空间进行一些其他非标准处理。

解决方案:

在样式表的顶部声明前缀:

<xsl:stylesheet
  version="2.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:nbase="urn:ietf:params:xml:ns:netconf:base:1.0"
  xmlns:junosi="http://xml.juniper.net/junos/12.3R8/junos-interface"
>

在 XPath 中使用这些前缀:
<xsl:for-each select="/nbase:rpc-reply/junosi:interface-information
                        /junosi:physical-interface/junosi:logical-interface">
  <tr>
    <td><xsl:value-of select="junosi:name"/></td>
  </tr>
</xsl:for-each>

关于xslt - 相同的 xpath 在命令行上有效,但在 xslt 中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28176470/

相关文章:

http - 错误 : universal match pattern ('/**' ) is defined before other patterns in the filter chain, 导致它们被忽略

c# - 如何删除 xmlns :xsd attribute but keep xmlns:xsi

javascript - 如何将 Document-Fragment 转换为 JavaScript 中的字符串内容?

javascript - 如何在 XSLT 中复制外部 CSS 和 JavaScript

html - xsl 为每个节点创建折叠/展开面板

xml - xpath表达式根据父属性选择子节点

asp.net - 根据参数应用不同的 XSLT 模板

xpath - 使用 Sahi 驱动程序使 CSS 选择器(第一个 child )在 Behat 3 中工作

python - 如何通过 Selenium python 登录到 yahoo(尝试了多种解决方案)

sql - 从 clob 数据类型 xml 值中提取数据