Re: [xsl] RE: loop elements based on attribute

Subject: Re: [xsl] RE: loop elements based on attribute
From: Martin Honnen <Martin.Honnen@xxxxxx>
Date: Thu, 14 Aug 2008 13:30:35 +0200
Kjellaug Johansen wrote:
Now, I've got another problem. I want a list of Pkt-elements to be
wrapped inside a List-element.

I want this xml:

<test>
<A>test</A>
 <Pkt type="pkt">Text</Pkt>
 <Pkt type="uavs">Text 1</Pkt>
 <Pkt type="pkt">More text</Pkt>
 <Pkt type="uavs">More text 1</Pkt>
 <Pkt type="uavs">More text 2</Pkt>
 <B>test</B>
 <A>test</A>
 <Pkt type="pkt">Lot of text</Pkt>
 <Pkt type="pkt">Tons of text</Pkt>
 <Pkt type="uavs">Tons of text 1</Pkt>
 </test>

To look like this:

<test>
 	<A>test</A>
 	<List>
		<Pkt type="pkt">Text</Pkt>
 		<Pkt type="uavs">Text 1</Pkt>
 		<Pkt type="pkt">More text</Pkt>
 		<Pkt type="uavs">More text 1</Pkt>
 		<Pkt type="uavs">More text 2</Pkt>
 	</List>
 	<B>test</B>
 	<A>test</A>
 	<List>
 		<Pkt type="pkt">Lot of text</Pkt>
 		<Pkt type="pkt">Tons of text</Pkt>
 		<Pkt type="uavs">Tons of text 1</Pkt>
	</List>
 </test>

Anybody who can help me?

Assuming you use XSLT 2.0 you can use xsl:for-each-group group-adjacent as follows:


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

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

  <xsl:template match="/test">
    <xsl:copy>
      <xsl:for-each-group select="*" group-adjacent="boolean(self::Pkt)">
        <xsl:choose>
          <xsl:when test="current-grouping-key()">
            <List>
              <xsl:copy-of select="current-group()"/>
            </List>
          </xsl:when>
          <xsl:otherwise>
            <xsl:copy-of select="current-group()"/>
          </xsl:otherwise>
        </xsl:choose>
      </xsl:for-each-group>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>
--

	Martin Honnen
	http://JavaScript.FAQTs.com/

Current Thread