1

I'm writing a program that produces an xml file. The code works perfectly giving the expected result.But it gives me only a single line document. I want it to be in formatted way and correctly indented.Is there a way to do that? Here is the code i used

public class Main {

    public static void main(String[] args) {
        WriteXml(7, 9, 0);
    }

    public static void WriteXml(int WS1, int FTP1, int EMAIL1) {

        try {
            final DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
            final DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
            final Document document = documentBuilder.newDocument();
            final Element root = document.createElement("Counter");
            document.appendChild(root);
            final Element properties = document.createElement("properties");
            root.appendChild(properties);

            final Element webservice = document.createElement("age");
            webservice.appendChild(document.createTextNode(Integer.toString(WS1)));
            properties.appendChild(webservice);

            final Element ftp = document.createElement("id");
            ftp.appendChild(document.createTextNode(Integer.toString(FTP1)));
            properties.appendChild(ftp);

            final Element email = document.createElement("grade");
            email.appendChild(document.createTextNode(Integer.toString(EMAIL1)));
            properties.appendChild(email);

            final TransformerFactory transformerFactory = TransformerFactory.newInstance();
            final Transformer transformer = transformerFactory.newTransformer();
            final DOMSource domSource = new DOMSource(document);
            final StreamResult streamResult = new StreamResult(new File("src/counter.xml"));
            transformer.transform(domSource, streamResult);

        } catch (final Exception e) {
            e.printStackTrace();
        }
    }
}

and this gives me the following xml document

<?xml version="1.0" encoding="UTF-8" standalone="no"?><Counter><properties><age>7</age><id>9</id><grade>0</grade></properties></Counter>

But i want it to be more like this

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Counter>
    <properties>
        <age>7</age>
        <id>9</id>
        <grade>0</grade>
    </properties>
</Counter>
Kaleb
  • 616
  • 1
  • 9
  • 22
  • Possible duplicate of [Pretty-printing output from javax.xml.transform.Transformer with only standard java api (Indentation and Doctype positioning)](http://stackoverflow.com/questions/1264849/pretty-printing-output-from-javax-xml-transform-transformer-with-only-standard-j) – Michael Lloyd Lee mlk Dec 01 '15 at 09:51
  • Underscore-java library has static method U.formatXml(xmlstring). – Valentyn Kolesnikov Mar 29 '20 at 08:08

3 Answers3

3

You may set several properties on the transformer's output, one of them is for indentation :

transformer.setOutputProperty(OutputKeys.INDENT, "yes");
Arnaud
  • 17,229
  • 3
  • 31
  • 44
3

With some guessing and after looking at this question adding these lines after obtaining the transformer might do the trick

transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
Community
  • 1
  • 1
Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
1

I created the following method:

public String prettyPrintXml(String xmlStringToBeFormatted) {
    String formattedXmlString = null;
    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setValidating(true);
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource inputSource = new InputSource(new StringReader(xmlStringToBeFormatted));
        Document document = documentBuilder.parse(inputSource);

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        StreamResult streamResult = new StreamResult(new StringWriter());
        DOMSource dOMSource = new DOMSource(document);
        transformer.transform(dOMSource, streamResult);
        formattedXmlString = streamResult.getWriter().toString().trim();
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
    }
    return formattedXmlString;
}
Benson Githinji
  • 559
  • 7
  • 10