Home >Java >javaTutorial >How Can I Beautify XML Strings in Java?
XML Beautification in Java
Question:
How can we enhance the readability and formatting of XML stored as a string in Java?
Introduction:
XML (Extensible Markup Language) often lacks proper indentation and line breaks, making it difficult to read and interpret. Formatting XML improves its readability and makes it easier to navigate and understand.
Code Solution:
Utilizing the Java API, we can format an XML string to make it more readable:
import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; public class XmlBeautifier { public static String formatXml(String unformattedXml) { try { // Create a transformer to modify the XML Transformer transformer = TransformerFactory.newInstance().newTransformer(); // Set indenting and indentation amount transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); // Convert the XML string to a DOM source DOMSource source = new DOMSource(new DocumentBuilder().parse(new InputSource(new StringReader(unformattedXml)))); // Format the XML and store the result in a string StreamResult result = new StreamResult(new StringWriter()); transformer.transform(source, result); return result.getWriter().toString(); } catch (TransformerException | ParserConfigurationException | SAXException e) { // Handle any exceptions throw new RuntimeException(e); } } }
Usage example:
String unformattedXml = "<tag><nested>hello</nested></tag>"; String formattedXml = XmlBeautifier.formatXml(unformattedXml);
Output Example:
<?xml version="1.0" encoding="UTF-8"?> <root> <tag> <nested>hello</nested> </tag> </root>
Notes:
The above is the detailed content of How Can I Beautify XML Strings in Java?. For more information, please follow other related articles on the PHP Chinese website!