XSLT 2.0-如何合并同级元素

时间:2018-06-29 17:19:20

标签: xml xslt

如何将具有相同类型的相邻同胞的特定元素合并到单个元素中?我觉得这应该很简单,但是找不到答案。

我的代码:

...
<nodeX>
  <a>words</a>
  <b>things</b>
  <g>hi</g>
  <g>there</g>
  <g>friend</g>
  <c>stuff</c>
  <g>yep</g>
</nodeX>
...

所需的输出:

...
<nodeX>
  <a>words</a>
  <b>things</b>
  <g>hi there friend</g>
  <c>stuff</c>
  <g>yep</g>
</nodeX>
...

我正在处理一个具有深层次结构的极其复杂且变化多端的文档,因此除了这些元素将在某种情况下显示以及与其他元素一起出现时,我无法进行许多假设。兄弟姐妹,这些兄弟姐妹需要合并。任何帮助将不胜感激。

更新:

根据zx485和Martin Honnen的建议,以下内容似乎可以很好地解开特定元素:

<xsl:template match="nodeX">
    <xsl:copy>
        <xsl:copy-of select="@*" />
        <xsl:for-each-group select="*" group-adjacent="name()">
            <xsl:choose>
                <xsl:when test="name()='g'">
                    <xsl:copy>
                        <xsl:copy-of select="current-group()/@*" />
                        <xsl:value-of select="current-group()"/>
                    </xsl:copy>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:apply-templates select="current-group()"/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:for-each-group>
    </xsl:copy>
</xsl:template>

1 个答案:

答案 0 :(得分:1)

对于XSLT-2.0,这并不困难。这是一个XSLT-2.0 Grouping问题。在这种情况下,请将xsl:for-each-group与属性group-adjacent一起使用。

以下模板匹配所有nodeX元素,并复制它们及其属性。迭代所有子元素,并按它们的name()对相邻元素进行分组。然后,它复制组中的第一个元素,并添加具有相同名称的所有元素的属性。现在,该组中所有元素的text() s用分隔符连接在一起-这是一个空格。

<xsl:template match="nodeX">
    <xsl:copy>
        <xsl:copy-of select="@*" />
        <xsl:for-each-group select="*" group-adjacent="name()">
            <xsl:copy>
                <xsl:copy-of select="current-group()/@*" />
                <xsl:value-of select="current-group()" separator=" " />
            </xsl:copy>
        </xsl:for-each-group>
    </xsl:copy>
</xsl:template> 

输出为:

<nodeX>
   <a>words</a>
   <b>things</b>
   <g>hi there friend</g>
   <c>stuff</c>
   <g>yep</g>
</nodeX>