質問

I was comment the present problem at this other one: the present is more complex because needs a recurrence. Detailing by example:

  <root>
    <c>cccc</c>
    <a gr="g1_1">aaaa</a>    <b gr="g1_1">1111</b>
    <a gr="g2_1" into="g1_1">bbbb</a>   <b gr="g2_1" into="g1_1">56565</b>
    <a gr="g3_1" into="g2_1">BB</a>   <b gr="g3_1" into="g2_1">55</b>
    <a gr="g1_2">xxxx</a>    <b gr="g1_2">2222</b>
    <a gr="g2_2" into="g1_2">wwww</a>   <b gr="g2_2" into="g1_2">3433</b>
  </root>

that must be enclosed by fold tags, resulting (after XSLT) in:

  <root>
    <c>cccc</c>

    <fold>
      <a gr="g1_1">aaaa</a>    <b gr="g1_1">1111</b>
      <fold><a gr="g2_1" into="g1_1">bbbb</a>   
            <b gr="g2_1" into="g1_1">56565</b>
            <fold><a gr="g3_1" into="g2_1">BB</a>   
                  <b gr="g3_1" into="g2_1">55</b>
            </fold>
       </fold>
    </fold>

    <fold>
      <a gr="g1_2">xxxx</a>    <b gr="g1_2">2222</b>
      <fold><a gr="g2_2" into="g1_2">wwww</a>   
            <b gr="g2_2" into="g1_2">3433</b>
      </fold>
    </fold>
  </root>

NOTES

The example have a "label for grouping" (@gr) and a label for "super-grouping" (@into pointing to the parent group).

The @gr is an ID for unique groups, and also indicates the "folding level" with the syntax "g" level "_" level-id, so, if need we can add an explicit attribute for folding level... Or can add and auxiliar structure (gdef as input metadata),

 <gdef>
  <group gr="g1_1" level="1" into=""/>
  <group gr="g2_1" level="2" into="g1_1"/>
  <group gr="g3_1" level="3" into="g2_1"/>
  <group gr="g1_2" level="1" into=""/>
  <group gr="g2_2" level="2" into="1_2"/>
 </gdef>

or etc.

役に立ちましたか?

解決

You don't need recursion. You just need to careful apply-templates to siblings.
The code below is an adaptation from the solution in your other (referred) question.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:strip-space elements="*" />
  <xsl:output indent="yes" />
  <xsl:key name="key" match="*[@gr]" use="@gr" />

  <xsl:template match="*[*/@gr]">
    <xsl:copy>
      <xsl:apply-templates select="*[not(@into)]"/><!--start by most top-level ones-->
    </xsl:copy>
  </xsl:template>
  <xsl:template match="*[@gr]"/>
  <xsl:template match="*[@gr][generate-id() = generate-id(key('key', @gr)[1])]">
    <fold>
      <xsl:for-each select="key('key', @gr)">
        <xsl:call-template name="identity" />
      </xsl:for-each>
      <xsl:apply-templates select="following-sibling::*[@into = current()/@gr]"/>
    </fold>
  </xsl:template>
  <xsl:template match="node()|@*" name="identity" >
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top