xmlxslt

How to split the book in the chapters format


In the below example we are trying split the book in the chapters format.

Can anyone help.

INPUT XML:

book.xml

<?xml version="1.0" encoding="UTF-8"?>
<book>
    <chapter id="1">
        <name>Laptop</name>
        <price>1200.00</price>
        <category>Electronics</category>
    </chapter>
    <chapter id="2">
        <name>Mouse</name>
        <price>25.00</price>
        <category>Electronics</category>
    </chapter>
</book>

REQUIRED OUTPUT:

chap01.xml

<?xml version="1.0" encoding="UTF-8"?>
<chapter id="1">
    <name>Laptop</name>
    <price>1200.00</price>
    <category>Electronics</category>
</chapter>

chap02.xml

<?xml version="1.0" encoding="UTF-8"?>
<chapter id="2">
    <name>Mouse</name>
    <price>25.00</price>
    <category>Electronics</category>
</chapter>

Solution

  • This will work for splitting into chapters. For the leading 0 on the filenames (i.e. chap01.xml, chap02.xml), you'll need to format the number where it is set in the href attribute.

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      version="2.0"
      xmlns:xs="http://www.w3.org/2001/XMLSchema"
      exclude-result-prefixes="#all">
      
      <xsl:template match="/book" >
        <xsl:for-each select="chapter" >
          <xsl:result-document href="chap{position()}.xml" >
            <xsl:sequence select="." />
          </xsl:result-document>
        </xsl:for-each>
      </xsl:template>
      
    </xsl:stylesheet>