tags:

views:

36

answers:

1

Hi,

My xml format is given below,

<SAMPLEFORM>
    <SAMPLE ID='1' TYPE='Normal'>
        <DATA>1</DATA>
    </SAMPLE>
    <SAMPLE TYPE='PageSplitter'>
        <DATA>N/A</DATA>
    </SAMPLE>
    <SAMPLE ID='2' TYPE='Normal'>
        <DATA>1</DATA>
    </SAMPLE>
</SAMPLEFORM>

I'm trying to split nodes into sets which contain the attribute Type='Normal' by defining the starting position. End position of the nodeset would be the next occurence of the node which contains the attribute Type='PageSplitter'.

Is there a way to get the position of a node without going through a for-each loop? And How to do the above?

+2  A: 

You don't need two kind of markers -- just one is sufficient:

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:key name="kPage" match="SAMPLE[not(@TYPE='Normal')]"
         use="generate-id(preceding-sibling::SAMPLE[@TYPE='Normal'][1])"/>

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

 <xsl:template match="SAMPLE[@TYPE='Normal']">
   <page>
     <xsl:copy-of select=".|key('kPage', generate-id())"/>
   </page>
 </xsl:template>

 <xsl:template match="SAMPLE[not(@TYPE='Normal')]"/>
</xsl:stylesheet>

when this transformation is applied on the following XML (The provided one, made well-formed, with one more element added, and with no "PAGESPLITTER"):

<SAMPLEFORM>
    <SAMPLE ID='1' TYPE='Normal'>
        <DATA>1</DATA>
    </SAMPLE>
    <SAMPLE ID='2'>
        <DATA>2</DATA>
    </SAMPLE>
    <SAMPLE ID='3' TYPE='Normal'>
        <DATA>3</DATA>
    </SAMPLE>
</SAMPLEFORM>

the wanted, correct result is produced:

<SAMPLEFORM>
    <page>
        <SAMPLE ID="1" TYPE="Normal">
            <DATA>1</DATA>
        </SAMPLE>
        <SAMPLE ID="2">
            <DATA>2</DATA>
        </SAMPLE>
    </page>
    <page>
        <SAMPLE ID="3" TYPE="Normal">
            <DATA>3</DATA>
        </SAMPLE>
    </page>
</SAMPLEFORM>
Dimitre Novatchev
@Dimitre: +1 good solution! I think you sould edit your malformed output... Ja!
Alejandro
@Alejandro: THanks for noticing this -- fixed the formatting.
Dimitre Novatchev