Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pretty print XML from Java?

I have a Java String that contains XML, with no line feeds or indentations. I would like to turn it into a String with nicely formatted XML. How do I do this?

String unformattedXml = "<tag><nested>hello</nested></tag>"; String formattedXml = new [UnknownClass]().format(unformattedXml); 

Note: My input is a String. My output is a String.

(Basic) mock result:

<?xml version="1.0" encoding="UTF-8"?> <root>   <tag>     <nested>hello</nested>   </tag> </root> 
like image 511
Steve McLeod Avatar asked Sep 26 '08 12:09

Steve McLeod


People also ask

How do I print an XML file?

Browse for the XML file by clicking File->Open or pressing Ctrl+O. Click File->Print or press Ctrl+P to open the Printer window.

Can you use XML with Java?

Java XML overviewThe Java programming language contains several methods for processing and writing XML. Older Java versions supported only the DOM API (Document Object Model) and the SAX (Simple API for XML) API. In DOM you access the XML document over an object tree. DOM can be used to read and write XML files.


2 Answers

Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); // initialize StreamResult with File object to save to file StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(doc); transformer.transform(source, result); String xmlString = result.getWriter().toString(); System.out.println(xmlString); 

Note: Results may vary depending on the Java version. Search for workarounds specific to your platform.

like image 200
Lorenzo Boccaccia Avatar answered Sep 17 '22 15:09

Lorenzo Boccaccia


Here's an answer to my own question. I combined the answers from the various results to write a class that pretty prints XML.

No guarantees on how it responds with invalid XML or large documents.

package ecb.sdw.pretty;  import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.XMLSerializer; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException;  import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer;  /**  * Pretty-prints xml, supplied as a string.  * <p/>  * eg.  * <code>  * String formattedXml = new XmlFormatter().format("<tag><nested>hello</nested></tag>");  * </code>  */ public class XmlFormatter {      public XmlFormatter() {     }      public String format(String unformattedXml) {         try {             final Document document = parseXmlFile(unformattedXml);              OutputFormat format = new OutputFormat(document);             format.setLineWidth(65);             format.setIndenting(true);             format.setIndent(2);             Writer out = new StringWriter();             XMLSerializer serializer = new XMLSerializer(out, format);             serializer.serialize(document);              return out.toString();         } catch (IOException e) {             throw new RuntimeException(e);         }     }      private Document parseXmlFile(String in) {         try {             DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();             DocumentBuilder db = dbf.newDocumentBuilder();             InputSource is = new InputSource(new StringReader(in));             return db.parse(is);         } catch (ParserConfigurationException e) {             throw new RuntimeException(e);         } catch (SAXException e) {             throw new RuntimeException(e);         } catch (IOException e) {             throw new RuntimeException(e);         }     }      public static void main(String[] args) {         String unformattedXml =                 "<?xml version=\"1.0\" encoding=\"UTF-8\"?><QueryMessage\n" +                         "        xmlns=\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message\"\n" +                         "        xmlns:query=\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/query\">\n" +                         "    <Query>\n" +                         "        <query:CategorySchemeWhere>\n" +                         "   \t\t\t\t\t         <query:AgencyID>ECB\n\n\n\n</query:AgencyID>\n" +                         "        </query:CategorySchemeWhere>\n" +                         "    </Query>\n\n\n\n\n" +                         "</QueryMessage>";          System.out.println(new XmlFormatter().format(unformattedXml));     }  } 
like image 44
Steve McLeod Avatar answered Sep 17 '22 15:09

Steve McLeod