我正在尝试使用XSLT呈现一个示例XML,如下所示:
<?xml version="1.0" encoding="UTF-16"?>
<root>
<title>test</title>
<description> This is the first description</description>
<description>This is for
<subject>testing</subject>every day
</description>
</root>
我使用以下XSLT代码来显示描述节点。
<xsl:for-each select="root/description">
<p><xsl:value-of select="."/></p>
</xsl:for-each>`
这就是我得到的输出。
This is the first description
This is for testing every day
你能建议一下,为什么它在第二个描述节点中显示测试吗?
测试在主题节点下。由于格式的原因,我想使用<xsl:value-of select="subject"/>
代码获取主题节点。
你能提出解决方案吗?
非常感谢。
问候,AK
在XSLT-1.0中,表达式<xsl:value-of select="."/>
选择所有子代节点的text()
值并将它们连接起来。要只选择所有直接的孩子,你必须为每个孩子申请另一个,如下所示:
<xsl:for-each select="root/description">
<p>
<xsl:for-each select="text()"> <!- Select all direct text() children -->
<xsl:value-of select="normalize-space(.)"/><xsl:text> </xsl:text>
</xsl:for-each>
</p>
</xsl:for-each>
然后,输出将如下:
<p>This is the first description </p>
<p>This is for every day </p>
EDIT(带附加要求(:
您可以将text()
节点与特定的父元素进行匹配:
<xsl:template match="/">
<xsl:for-each select="root/description">
<p><xsl:apply-templates select="node()|@*" /></p>
</xsl:for-each>
</xsl:template>
<xsl:template match="text()">
<xsl:value-of select="normalize-space(.)"/><xsl:text> </xsl:text>
</xsl:template>
<xsl:template match="subject/text()">
<b><xsl:value-of select="normalize-space(.)"/></b>
</xsl:template>
输出为:
<p>This is the first description </p>
<p>
This is for <b>testing</b>
every day </p>
这种方法可以在输出中添加突出显示元素。但我不知道如何去除多余的空间,所以这(也许(是最好的。
xsl:value-of
只能创建字符串。如果希望subject
元素包含在输出中,请使用xsl:copy-of
而不是xsl:value-of
。