Transforming XML in Java is achieved using a Transformer. To use an XSL file for the transformation involves first creating Templates instance which can then be used to create the required Transformer.
TransformerFactory factory = TransformerFactory.newInstance();
Templates template = factory.newTemplates(
new StreamSource(new FileInputStream(xslPath)));
Transformer transformer = template.newTransformer();
Source source = new StreamSource(new FileInputStream(xmlInputPath));
Result result = new StreamResult(new FileOutputStream(xmlOutputPath));
transformer.transform(source, result);
written by objects
\\ tags: Templates, transform, Transformer, xsl
XSL is great for transforming an XML file. The following XSL can be used to convert all element names into lower case.
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:variable
name="lcase">abcdefghijklmnopqrstuvwxyz</xsl:variable>
<xsl:variable
name="ucase">ABCDEFGHIJKLMNOPQRSTUVWXYZ</xsl:variable>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{translate(local-name(),$ucase,$lcase)}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
How to transform XML using XSL may also be of interest to you.
written by objects
\\ tags: xsl
Use an XSL transformation with the xsl:strip-space instruction.
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(
new StreamSource("strip-space.xsl"));
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
written by objects
\\ tags: Transformer, xml, xsl
Recent Comments