Currently I am working on parsing and transforming of xml. So I was searching the internet for some examples concerning xml transformation with xslt. Many examples can be found but most of them didn't fit my needs, because they write the output of the transformation directly to file using a StreamResult and I need the result as a DOM.
Initially this does not look very difficult: just use a DOMResult, et voila. But reality is a bit tougher because the DOMResult object only provides a getNode() method which cannot 'imported' in a new org.w3c.Document directly. It requires a little 'trick':
...
URI uriXslt;
Document inputDoc;
Document transformedDoc
...
// read the xslt from an URI
StreamSource xslt = new StreamSource(uriXslt.toString());
TransformerFactory tFactory = TransformerFactory.newInstance();
// 'make' a transformer based on the xslt
Transformer tf = tFactory.newTransformer(xslt);
DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dFactory.newDocumentBuilder();
// 'make' the result Document
transformedDoc = dBuilder.newDocument();
// define the input and the output of the transformation (the inputDoc is a org.w3c.Document)
DOMSource src = new DOMSource (inputDoc);
DOMResult res = new DOMResult (transformedDoc);
// perform the transformation
tf.transform (src, res);
...
Posted by at 11:44