How to format or indent an xml string

The following method indents xml using 4 spaces (per indention/tab).

public static String toFormattedXml(String xml) {
        try {
                XmlOptions options = new XmlOptions();
                options.setSavePrettyPrint();
                options.setSavePrettyPrintIndent(4);
                XmlObject formatter = XmlObject.Factory.parse(xml, options);
                byte[] byteArray = xml.getBytes();
                ByteArrayOutputStream out = new ByteArrayOutputStream(byteArray.length);
                formatter.save(out, options);
                return out.toString();
        } catch (IOException e) {
                System.err.println("IOException while creating ByteArrayOutputStream for formatting xml.", e);
        }
}

Page Comments (Click to edit)






[Click to add or edit comments])

Please prepend comments below including a date

Design by N.Design Studio, adapted by solidGone.org (version 1.0.0)
Have a nice day.