How to split XML file into many XML files using XSLT
I would like to know how to write XSLT to split an XML file into multiple XML files according to these requirements:
- file1.xml - The lakes who type= Natyral
- file2.xml - The lakes who type=Artificial
- file3.xml - The lakes who type=Glacial
XML imput file is:
<Lakes>
<Lake>
<id>1</id>
<Name>Caspian</Name>
<Type>Natyral</Type>
</Lake>
<Lake>
<id>2</id>
<Name>Moreo</Name>
<Type>Glacial</Type>
</Lake>
<Lake>
<id>3</id>
<Name&开发者_开发百科gt;Sina</Name>
<Type>Artificial</Type>
</Lake>
</Lakes>
Use XSLT 2.0, like this stylesheet:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<xsl:for-each-group select="Lakes/Lake" group-by="Type">
<xsl:result-document href="file{position()}.xml">
<Lakes>
<xsl:copy-of select="current-group()"/>
</Lakes>
</xsl:result-document>
</xsl:for-each-group>
</xsl:template>
</xsl:stylesheet>
Note: xsl:result-document
instruction.
With standard XSL it is not possible to have more than one output xml (i.e. resulting tree).
However, using Xalan redirect extension, you can.
Have a look at the example on the page in the link. I tested the following with Xalan Java 2.7.1
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:redirect="http://xml.apache.org/xalan/redirect" extension-element-prefixes="redirect">
<xsl:output method="xml" indent="yes" />
<xsl:template match="/">
<xsl:apply-templates />
</xsl:template>
<xsl:template match="/Lakes/Lake[Type='Natyral']">
<redirect:write file="/home/me/file1.xml">
<NatyralLakes>
<xsl:copy-of select="." />
</NatyralLakes>
</redirect:write>
</xsl:template>
<xsl:template match="/Lakes/Lake[Type='Artificial']">
<redirect:write file="/home/me/file1.xml">
<ArtificialLakes>
<xsl:copy-of select="." />
</ArtificialLakes>
</redirect:write>
</xsl:template>
<xsl:template match="/Lakes/Lake[Type='Glacial']">
<redirect:write file="/home/me/file3.xml">
<GlacialLakes>
<xsl:copy-of select="." />
</GlacialLakes>
</redirect:write>
</xsl:template>
</xsl:stylesheet>
精彩评论