Oops Null Pointer

Java programming related

Category Archives: XSLT

Quick guide to transforming XML with XSLT

As a reminder to myself for a quick pattern for transforming XML via XSLT:

Some setup:


public static final String XML_HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
public static final String XSL_HEADER = "<xsl:stylesheet version=\"1.0\" " +
    "xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">";
public static final String ID_XFORM = "<xsl:template match=\"@*|node()\"><xsl:copy>" +
    "<xsl:apply-templates select=\"@*|node()\"/></xsl:copy></xsl:template>";

public static final String TRANS_ATTR = "<xsl:template match=\"ATTR_PATH@ATTR_NAME\">" +
    "<xsl:attribute name=\"ATTR_NAME\">ATTR_VALUE</xsl:attribute></xsl:template>";
public static final String XSL_END = "</xsl:stylesheet>";
public static final String XFORM_ATTR_XSL = XML_HEADER + XSL_HEADER + ID_XFORM + TRANS_ATTR + XSL_END;

And a usage sample transforming an attribute’s value:

String xsl = XFORM_ATTR_XSL.replace("ATTR_PATH", "");
xsl = xsl.replace("ATTR_NAME", "myAttribute");
xsl = xsl.replace("ATTR_VALUE", "newValue");

ByteArrayInputStream xslInputStream = new ByteArrayInputStream(xsl.getBytes("UTF-8"));
FileInputStream xml = new FileInputStream(new File("myXmlFile");
InputStream transformedXml = null;

try {
    transformedXml = transformXml(xml, xslInputStream);
}
finally {
    if (xml != null) xml.close();
}

and the transform method:

private InputStream transformXml(InputStream xml, InputStream xsl) throws TransformerConfigurationException, TransformerException {

    TransformerFactory factory = new org.apache.xalan.processor.TransformerFactoryImpl();
    Transformer transformer = factory.newTransformer(new StreamSource(xsl));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    transformer.transform(new StreamSource(xml), new StreamResult(baos));
    return new ByteArrayInputStream(baos.toByteArray());
}
Advertisements