Reputation: 3751
I have an XSLT file that I want to use to create two separate XML files/Strings. The problem is I can't use the same template matching.
If I have this:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="Frame/AAA">
<xsl:for-each select=".">
<Frame xmlns="MyNamespace.com">
<BBB>
<!-- Stuff here -->
</BBB>
</Frame>
</xsl:for-each>
</xsl:template>
<xsl:template match="Frame/AAA">
<xsl:for-each select=".">
<Frame xmlns="MyNamespace.com">
<WWW>
<!-- Stuff here -->
</WWW>
</Frame>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
XML file:
<Frame>
<AAA>
<!-- Stuff here -->
</AAA>
<Frame>
So I want to use both templates and create two XML files. However, using two of the same templates is not allowed as it won't know where to look.
This is the Java code I use to create the XML files:
// Get stylesheet (xslt) and xml data file
File stylesheet = new File(xsltFilepath);
InputSource inputSource = new InputSource(new ByteArrayInputStream(xmlString.getBytes()));
// Turn data file into document
Document document = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(inputSource);
// Hold XML markup
StreamSource stylesource = new StreamSource(stylesheet);
// Turn source into a transformer object
Transformer transformer = TransformerFactory.newInstance().newTransformer(stylesource);
// Convert to a string
StringWriter stringWriter = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
// Return the string
return tringWriter.toString();
How can I achieve what I want?
Upvotes: 0
Views: 186
Reputation: 167726
If you use XSLT 2.0 and modes you can use e.g.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<xsl:apply-templates/>
<xsl:apply-templates mode="m2"/>
</xsl:template>
<xsl:template match="Frame/AAA">
<Frame xmlns="MyNamespace.com">
<BBB>
<!-- Stuff here -->
</BBB>
</Frame>
</xsl:template>
<xsl:template match="Frame/AAA" mode="m2">
<xsl:result-document href="result2.xml">
<Frame xmlns="MyNamespace.com">
<WWW>
<!-- Stuff here -->
</WWW>
</Frame>
</xsl:result-document>
</xsl:template>
</xsl:stylesheet>
Upvotes: 1