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

标签 xslt return

我有像这样的 xml:

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

如何返回 <item id="1"> 的文本('文本1')?<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>

我不知道还要输入什么来提交我的编辑

最佳答案

How to return text of <item id="1">('Text1')? <xsl:value-of select="item/text()"/> returns nothing.


item element 有多个 text-node 子节点,其中第一个恰好是全空白的——这就是为什么你“什么都没有”。

测试节点的字符串值是否不是全空白的一种方法是使用 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

关于xslt - 如何返回没有子节点文本的节点文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16134646/

相关文章:

xml - XSLT 列表前 50

xslt - 如何最好地用 Diazo 替换链接文本

xml - 我的 XSLT 中有什么错误?

java - 返回函数和存储变量有什么区别?

javascript - 如何映射一个对象并在对象 javascript/reactjs 中呈现数组?

javascript - Google 跟踪代码管理器自定义变量返回未定义

html - 在 Mac 上将 plist xml 文件转换为 html/pdf 格式

c++ - 如何在 C++ 中返回 Null 作为引用?

python - 如何在python中重复找到T个数字中每个数字的数字和,直到它成为一位数字?

xslt - 在 XSLT 中的值周围加上双引号