xPath提取节点问题

时间:2016-01-18 11:14:43

标签: xml xslt xpath

我有这个XML文件:

<produce>
    <item>apple</item>
    <item>banana</item>
    <item>pepper</item>
    <item>apples</item>
    <item>pizza</item>
</produce>

我想要仅提取项目的名称,例如苹果,香蕉,胡椒,苹果和披萨,因此我创建了这个XSL文件:

  <?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="1.0">
  <xsl:output method="html"/>

  <xsl:template match="/">
    <html>
    <body>
    <ul>
    <li><xsl:value-of select="text()"/></li>
    </ul>
    </body>
    </html>
  </xsl:template>

</xsl:stylesheet>

但我不明白为什么它不起作用。 也许我不明白作用text()的作用。 你能救我吗?

1 个答案:

答案 0 :(得分:0)

目前,您正在li输出当前节点,该节点是顶级文档节点。 text()函数将获取作为当前节点的直接子节点的文本节点。但是在您的XML中,您想要的文本节点是item元素的子节点。

如果您希望XML中的每个li都有item,则首先需要使用itemxsl:for-each选择这些xsl:apply-templates元素。

试试这个XSLT

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="1.0">
  <xsl:output method="html"/>

  <xsl:template match="/">
    <html>
    <body>
    <ul>
    <xsl:for-each select="produce/item">
        <li><xsl:value-of select="text()"/></li>
    </xsl:for-each>
    </ul>
    </body>
    </html>
  </xsl:template>

</xsl:stylesheet>
相关问题