xsl-list
[Top] [All Lists]

Re: [xsl] another placement of nodes question

2010-01-25 12:32:33
a kusa wrote:

Please note that every item under level2 becomes a step2 in my output XML.

You have not really spelled out whether there can be more elements like level2.
Assuming there can be more like e.g. in

<root>
<level1>
<st1>
<desc><text>sample desc</text></desc>
<!-- A <spec> element can occur here as well-->
<level2>
<item><text>r1 </text></item>
<item><text>r2</text></item>
</level2>
<spec><para>Some spec 1</para></spec>
<spec><para>Some spec 2</para></spec>

<level2>
<item><text>r3 </text></item>
<item><text>r4</text></item>
</level2>
<spec><para>Some spec 3</para></spec>
<spec><para>Some spec 4</para></spec>

</st1>
</level1>
</root>

and you want to transform that into e.g.

<root>
   <step1>
      <text>sample desc</text>
      <step2>
         <text>r1 </text>
      </step2>
      <step2>
         <text>r2</text>
         <spec>
            <para>Some spec 1</para>
         </spec>
         <spec>
            <para>Some spec 2</para>
         </spec>
      </step2>
      <step2>
         <text>r3 </text>
      </step2>
      <step2>
         <text>r4</text>
         <spec>
            <para>Some spec 3</para>
         </spec>
         <spec>
            <para>Some spec 4</para>
         </spec>
      </step2>
   </step1>
</root>

then you can change the stylesheet posted earlier to use XSLT 2.0 grouping as follows:

<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
  version="2.0">

  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

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

  <xsl:template match="st1/desc | st1/level2">
    <xsl:apply-templates/>
  </xsl:template>

  <xsl:template match="level1">
    <step1>
      <xsl:for-each-group select="st1/*" group-starting-with="level2">
        <xsl:apply-templates select="."/>
      </xsl:for-each-group>
    </step1>
  </xsl:template>

  <xsl:template match="level2/item">
    <step2>
      <xsl:apply-templates/>
    </step2>
  </xsl:template>

  <xsl:template match="level2/item[last()]" priority="3">
    <step2>
      <xsl:apply-templates/>
      <xsl:copy-of select="current-group()[self::spec]"/>
    </step2>
  </xsl:template>

  <xsl:template match="st1/spec"/>

</xsl:stylesheet>



--

        Martin Honnen
        http://msmvps.com/blogs/martin_honnen/

--~------------------------------------------------------------------
XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list
To unsubscribe, go to: http://lists.mulberrytech.com/xsl-list/
or e-mail: <mailto:xsl-list-unsubscribe(_at_)lists(_dot_)mulberrytech(_dot_)com>
--~--

<Prev in Thread] Current Thread [Next in Thread>