Explore Courses Blog Tutorials Interview Questions
0 votes
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"?>






1 Answer

0 votes
by (46k points)


Transformer transformer = TransformerFactory.newInstance().newTransformer();

transformer.setOutputProperty(OutputKeys.INDENT, "yes");

transformer.setOutputProperty("{}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();


 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
asked Nov 12, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Nov 4, 2019 in Java by Anvi (10.2k points)

Browse Categories