使用xslt逻辑合并节点值

时间:2014-07-15 08:34:44

标签: xml xslt xslt-1.0 xslt-2.0 xslt-grouping

如何使用xslt 1.0和xslt 2.0将xml以下转换为给定输出。 请参考给定的输入和输出............. 输入: -

<block>
    <line>
        <formatting>
            <word>text 1</word>
        </formatting>
        <formatting bold="1">
            <word>text 2</word>
        </formatting>
        <formatting bold="1">
            <word>text 3</word>
        </formatting>
        <formatting bold="1">
            <word>text 4</word>
        </formatting>
        <formatting>
            <word>text 5</word>
        </formatting>
        <formatting bold="1">
            <word>text 6</word>
        </formatting>
        <formatting bold="1">
            <word>text 7</word>
        </formatting>
        <formatting>
            <word>text 8</word>
        </formatting>
        <formatting>
            <word>text 9</word>
        </formatting>
        <formatting bold="1">
            <word>text 10</word>
        </formatting>
        <formatting>
            <word>text 11</word>
        </formatting>
    </line>
</block>

输出应为: -

<p>text 1 <b>text 2 text 3 text 4</b> text 5 <b>text 6 text 7</b> text 8 text 9 <b>text 10</b> text 11</p>

需要xslt 1.0中的代码

1 个答案:

答案 0 :(得分:2)

使用XSLT 2.0和像Saxon 9这样的XSLT 2.0处理器,您可以使用for-each-group group-adjacent

<xsl:stylesheet 
  version="2.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  exclude-result-prefixes="xs">

<xsl:template match="line">
  <p>
    <xsl:for-each-group select="formatting" group-adjacent="string(@bold)">
      <xsl:if test="position() gt 1"><xsl:text> </xsl:text></xsl:if>
      <xsl:choose>
        <xsl:when test="current-grouping-key() = '1'">
          <b>
            <xsl:value-of select="current-group()/word"/>
          </b>
        </xsl:when>
        <xsl:otherwise>
          <xsl:value-of select="current-group()/word"/>
        </xsl:otherwise>

      </xsl:choose>
    </xsl:for-each-group>
  </p>
</xsl:template>

</xsl:stylesheet>