How do I print XML data in Java in a good way?

Asked 2 years ago, Updated 2 years ago, 150 views

There is a Java string that has no line feed and is not indented. I want to make this string look good. How shall I do it?

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

Note: Input plot string and output plot string .

pretty-print java xml

2022-09-22 21:36

1 Answers

Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//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 vary depending on the Java version. Search for solutions based on the platform.


2022-09-22 21:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.