XSLT:XML 节点呈现问题

时间:2021-06-16 00:24:07

标签: xml xslt xpath xml-parsing

我正在尝试使用 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

能否请您提出建议,为什么它在第二个描述节点中显示测试

testing 位于主题节点下。由于格式问题,我想使用 <xsl:value-of select="subject"/> 代码获取主题节点。

你能提出什么可能的解决方案吗?

非常感谢。

问候,AK

2 个答案:

答案 0 :(得分:1)

在 XSLT-1.0 中,表达式 <xsl:value-of select="."/> 选择所有 后代 节点的 text() 值并将它们连接起来。要仅选择所有直接子级,您必须像这样应用另一个 for-each:

<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>

编辑(附加要求):

您可以将 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>

这种方法可以在输出中添加高亮元素。但我不知道如何去除多余的空间,所以这(也许)已经够好了。

答案 1 :(得分:0)

xsl:value-of 只能创建字符串。如果您希望在输出中包含 subject 元素,请使用 xsl:copy-of 而不是 xsl:value-of