Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.9k points)

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>

1 Answer

0 votes
by (46k points)

Try:

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);

 Results may differ depending on the Java version. Seek for workarounds particular to your platform.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Sep 30, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Jul 26, 2019 in Java by Shubham (3.9k points)

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...