简体   繁体   中英

Breaking nodes into pages in XSLT

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?

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">
    <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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM