Customize your XML using Transform

A colleague of mine had a problem when generating an XML file (that he could not solve neither using XMLBeans nor using JAXB): his issue was to add a standalone=”no” in the XML file declaration (to be compliant with a third party specifications). You have to know that when setting standalone attribute to “no”, both libraries simply ignore that attribute (cause it’s the default value) and there is no way to get around that. We (I’d rather say He) have found a solution using the javax.xml.transform.Transformer class. In few words, this class allows you to transform a tree representation onto another tree representation, customizing and overriding any field attribute transformation.

Here is the way we achieved our goal (setting standalone=”on”) that could serve as a base usage example:

// get a new instance
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // to properly indent XML
StreamResult output = new StreamResult(new FileWriter(file2)); // output file to transform
StreamSource source = new StreamSource(file); // input file to transform
transformer.transform(source, output);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s