0

I have this XML in one file below

<?xml version="1.0" encoding="utf-8"?>
<document>
  <file> <!--File1.xml-->
    <content>content file 1</content>
  </file>
  <file> <!--File2.xml-->
    <content>content file 2</content>
  </file>
  <file> <!--File3.xml-->
    <content>content file 3</content>
  </file>
</document>

How do I write an XSLT to break it to multiple files like below

File1.xml
<?xml version="1.0" encoding="utf-8"?>
<document>
  <file>
    <content>content file 1</content>
  </file>
</document>

File2.xml
<?xml version="1.0" encoding="utf-8"?>
<document>
  <file> 
    <content>content file 2</content>
  </file>
</document>

etc..

Thank you for help.

4
  • Are you able to use XSLT 2.0? If so, you should be able to use "result-document". See saxonica.com/documentation/xsl-elements/result-document.html Commented Jun 24, 2014 at 8:32
  • I believe we can only use XSLT 1.0. :( Commented Jun 25, 2014 at 1:49
  • Do you actually have to use XSLT at all here? If you are using using .Net for the transformation, just load the XML into an XDocument, select all the file elements, iterate over them and output a file for each one. Commented Jun 25, 2014 at 7:22
  • Yes can do that also but it is the requirement for me to use XSLT because a file can contain more or less data depending on their requirement Commented Jun 25, 2014 at 7:27

1 Answer 1

2

With XSL 2.0:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>
    <xsl:template match="/">
        <xsl:for-each select="document/file">
            <xsl:result-document href="file{position()}.xml">
                <document>
                    <xsl:copy-of select="current()"/>
                </document>
            </xsl:result-document>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

I tested this using Saxon, which supports XSLT 2.0, using the command below:

java -jar saxon9.jar -xsl:transform.xsl -s:input.xml

This command generates three files: file1.xml, file2.xml and file3.xml.

$ cat file1.xml
<?xml version="1.0" encoding="UTF-8"?>
<document>
   <file> <!--File1.xml-->
    <content>content file 1</content>
  </file>
</document>
Sign up to request clarification or add additional context in comments.

3 Comments

How about in XSL 1.0, is it doable?
Because as much as possible we want to avoid using third party components. We are using .Net for the transformation. Thanks
Not in XSL 1.0. The other alternative is to use xml parsing in .Net. For example, use an xpath (/document/file) to get all the file elements and then iterate over them, writing each one out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.