如何返回没有子节点文本的节点文本

时间:2013-04-21 18:23:40

标签: xslt return

我有xml,如:

<item id="1">
        <items>
            <item id="2">Text2</item>
            <item id="3">Text3</item>
        </items>Text1
</item>

如何返回<item id="1">('Text1')的文字? <xsl:value-of select="item/text()"/>不返回任何内容。

我的XSLT是:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="w3.org/1999/XSL/Transform">

  <xsl:template match="/">
    <html>
      <body>
         <xsl:apply-templates select="item"/>
     </body>
    </html>
  </xsl:template>

  <xsl:template match="item">
     <xsl:value-of select="text()"/>
  </xsl:template>
</xsl:stylesheet>

我不知道还有什么可以输入我的编辑

2 个答案:

答案 0 :(得分:3)

  

如何返回<item id="1">('Text1')的文字? <xsl:value-of select="item/text()"/>不返回任何内容。

item元素有多个文本节点子节点,其中第一个恰好是一个空白节点 - 这就是为什么你“无所事事”。

测试节点的字符串值是否不是全空白的一种方法是使用normalize-space()函数。

在单个Xpath表达式中,您需要此

/*/text()[normalize-space()][1]

这是一个完整的转换,其结果是所需的文本节点:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/*">
  <xsl:copy-of select="text()[normalize-space()][1]"/>
 </xsl:template>
</xsl:stylesheet>

在提供的XML文档上应用此转换时:

<item id="1">
        <items>
            <item id="2">Text2</item>
            <item id="3">Text3</item>
        </items>Text1
</item>

产生了想要的正确结果:

Text1

答案 1 :(得分:2)

这通常应该有效:

<xsl:apply-templates select="item/text()" />

合并到您的XSLT中:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:key name="item_key" match="item" use="."/>
  <xsl:strip-space elements="*" />

  <xsl:template match="/">
    <html>
      <body>
        <ul>
          <xsl:apply-templates select="item"/>
        </ul>
      </body>
    </html>
  </xsl:template>
  <xsl:template match="item">
    <li>
      <xsl:apply-templates select="text()"/>
    </li>
  </xsl:template>
</xsl:stylesheet>

在样本输入上运行时,结果为:

<html>
  <body>
    <ul>
      <li>Text1
</li>
    </ul>
  </body>
</html>

或者,这也应该有效:

<xsl:copy-of select="item/text()" />