XSLT:递归合并相同名称的节点

3

虽然stackoverflow上有很多标题相似的问题,但我没有找到我特定问题的答案。

假设我有一个xml树:

<input>
    <a>
        <b>
            <p1/>
        </b>
    </a>
    <a>
        <b>
            <p2/>
        </b>
    </a>
</input>

我希望把它变成这样

<input>
    <a>
        <b>
            <p1/>
            <p2/>
        </b>
    </a>
</input>

这种转换的想法是将树形结构转换为更加“规范”的树形结构,其中每个节点只能有一个具有相同名称的子节点(与文件系统相比较)。

我尝试使用 xslt-2 的分组功能,但无法使递归正常工作。

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
  <xsl:strip-space elements="*"/>
    <xsl:template match="/">
        <output>
            <xsl:apply-templates select="*"/>
        </output>
    </xsl:template>

  <!-- this merges the children -->
  <xsl:template name="merge" match="*">

      <xsl:for-each-group select="child::*" group-by="local-name()">
          <xsl:variable name="x" select="current-grouping-key()"/>
          <xsl:element name="{$x}">
              <xsl:copy-of select="current-group()/@*"/>
              <xsl:apply-templates select="current-group()"/>
              <xsl:copy-of select="text()"/>
          </xsl:element>
      </xsl:for-each-group>
  </xsl:template>
</xsl:stylesheet>

我看到问题在于我对current-group()中的每个节点分别应用模板,但我不知道如何先将这个集合“连接”起来,然后一次性应用模板。


答案 https://dev59.com/4Izda4cB1Zd3GeqPnH2L#31157107 没有帮到您吗? - Martin Honnen
1个回答

0

我认为你可以使用分组设置一个函数,参见http://xsltransform.net/bdxtqM/1,它可以实现

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"
  xmlns:mf="http://example.com/mf"
  exclude-result-prefixes="mf">

  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="@* | node()">
      <xsl:copy>
          <xsl:apply-templates select="@* | node()"/>
      </xsl:copy>
  </xsl:template>

  <xsl:function name="mf:merge" as="node()*">
    <xsl:param name="elements" as="element()*"/>
    <xsl:for-each-group select="$elements" group-by="node-name(.)">
        <xsl:copy>
            <xsl:copy-of select="current-group()/@*"/>
            <xsl:sequence select="mf:merge(current-group()/*)"/>
        </xsl:copy>
    </xsl:for-each-group>
  </xsl:function>

  <xsl:template match="/*">
    <xsl:copy>
      <xsl:sequence select="mf:merge(*)"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

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