Thursday, December 23, 2010

Pretty print Xml

If you want to format your Xml..theres lots of ways

This url uses Xerces

(it also uses jtidy which I could not get to work with pure XML.. (kept adding HTML tags).

If you want to avoid xerces and just stick to standard java then you need to use the Transformer.

Just to note that top rated answer requires the use of xerces.

If you don't want to add this dependency then you can simply use the standard jdk libraries.

(Note if an error occurs this will return the original text)



import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;

import org.xml.sax.InputSource;

public class Test {
public static void main(String[] args) {
Test t = new Test();
System.out.println(t.formatXml("text D"));

public String formatXml(String xml){
Transformer serializer= SAXTransformerFactory.newInstance().newTransformer();
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
Source xmlSource=new SAXSource(new InputSource(new ByteArrayInputStream(xml.getBytes())));
StreamResult res = new StreamResult(new ByteArrayOutputStream());
serializer.transform(xmlSource, res);
return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray());
}catch(Exception e){
//TODO log error
return xml;


No comments: