使用XSLT检测节点与其后续兄弟节点之间的空格或文本

3

我有一个XML文档,其中包含以下示例摘录:

<p>
    Some text <GlossaryTermRef href="123">term 1</GlossaryTermRef><GlossaryTermRef href="345">term 2</GlossaryTermRef>.
</p>

我正在使用以下模板将此转换为XHTML:

我正在使用XSLT技术进行转换:

<xsl:template match="GlossaryTermRef">
    <a href="#{@href}" class="glossary">
        <xsl:apply-templates select="node()|text()"/>
    </a>
</xsl:template>

这个方法很有效,但是如果两个相邻的GlossaryTermRef元素出现在一起,我需要在它们之间插入一个空格?

有没有办法检测当前节点和下一个兄弟节点之间是否有空格或文本?我不能总是插入一个空格GlossaryTermRef项,因为它可能后面跟着标点符号。

3个回答

3
我成功地通过修改模板来解决了这个问题,具体方法如下:
<xsl:template match="GlossaryTermRef">
    <a href="#{@href}" class="glossary">
        <xsl:apply-templates select="node()|text()"/>
    </a>
    <xsl:if test="following-sibling::node()[1][self::GlossaryTermRef]">
        <xsl:text> </xsl:text>
    </xsl:if>
</xsl:template>

有没有人能提出更好的方法,或者看到这种解决方案有什么问题?

2
首先,“node()|text()”是“node()”的冗长等价形式。也许你的意思是“*|node()”,这将选择元素和文本子节点,但不包括注释或PI。
您的解决方案可能与其他任何解决方案一样好。另一个解决方案是使用分组:
<xsl:for-each-group select="node()" group-adjacent="boolean(self::GlossaryTermRef)">
  <xsl:choose>
    <xsl:when test="current-grouping-key()">
      <xsl:for-each select="current-group()">
        <xsl:if test="position() gt 1"><xsl:text> </xsl:text></xsl:if>
        <xsl:apply-templates select="."/>
      </xsl:for-each>
    </xsl:when>
    <xsl:otherwise>
     <xsl:apply-templates select="current-group()"/>
    </xsl:otherwise>
  </xsl:choose>
</xsl:for-each-group>

哎呀,这样做一点也不好看。

我的下一个尝试将是使用同级递归(即父元素对第一个子元素应用模板,每个子元素对紧随其后的兄弟元素应用模板),但我认为这也不会有所改善。


0
这个怎么样?你有什么感觉?
<xsl:template match="GlossaryTermRef">
<a href="#{@href}" class="glossary">
<xsl:apply-templates select="node()|text()"/>
</a>
</xsl:template>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接