我有这样的 xml:
<article>
<title> Test title - <literal> Compulsory - </literal> <fn> ABC </fn>
<comments> a comment</comments>
</title>
</article>
我想在变量中获取所有子节点+自身文本 例如
$full_title = "Test title - Compulsory - ABC"
Except comments node text.
Following is my unsuccessful try where i miss title node text.
<xsl:template name="test">
<xsl:variable name="full_title" select="article/title/*[not(self::comments)][1]" />
<xsl:variable name="width" select="45" />
<xsl:choose>
<xsl:when test="string-length($full_title) > $width">
<xsl:value-of select="concat(substring($full_title,1,$width),'..')"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$full_title"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
最佳答案
更改 *
至 node()
.这将选择作为 <title>
子元素的元素和文本节点。元素。然后取出[1]
因为你想要 <title>
的所有个 child :
<xsl:variable name="full_title"
select="string-join(article/title/node()[not(self::comments)], '')" />
一种更可靠的方法,这样如果您在 <title>
下有多个级别,您就不会被绊倒和 <comments>
元素作为孙子出现,将是这样的:
<xsl:variable name="full_title"
select="string-join(article/title//text()[not(ancestor::comments)], '')" />
更新:
由于您希望变量保存一个字符串值,并且由于您将它传递给类似 concat()
的函数和 string-length()
它不能将多个节点的序列作为第一个参数,使用 string-join(..., '')
围绕序列通过连接每个节点的字符串值将其转换为字符串。
关于XSLT 选择除一个子节点文本之外的所有文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17995770/