XSLT and Java Quick Tips (Xalan)
Recently at work, I’ve been using XSLT transforms in our backend quite a bit. But the issues I’ve run into took stupid amounts of effort to resolve and it wasnt easy to find any kind of list of do’s and dont’s – so I’m gonna make one from the stuff I’ve just discovered!
- When dealing with DOMSource and DOMResult – always setNamespaceAwareness(true) on your DocumentBuilder/DocumentBuilderFactory !!! – otherwise you end up with empty Documents and no indicators as to why!
- Remember that an XSLT transformation is not guaranteed to return an XML document! Hence, Don’t automatically assume a DOMResult( docBuilder.newDocument() ) will return a valid object – if your XSLT doesn’t produce valid XML, you’ll get an empty DOMResult document node!
- Validation settings affect whitespace awareness – if you don’t have validation on, whitespace is NOT ignored, so make sure your XSLT is formatted correctly – the most common problem area is when you try to prettyfy your .xsl file using indentation etc. Remember that XSL is pretty much an in-place tempate file [Copy Contents -> Replace Stuff exactly where it's asked for -> Dump result!]
Lastly, and easy way to transform input XML and pretty print it.
TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); Document doc = buildXml(); /* get your XML document from somewhere.. */ StringWriter stringWriter = new StringWriter(); StreamResult result = new StreamResult(stringWriter); DOMSource source = new DOMSource(doc); trans.transform(source, result); System.out.println(stringWriter.toString());

2 Comments
leave a commentTrackbacks and Pingbacks