Home > Java > javaTutorial > How Can I Beautify XML Strings in Java?

How Can I Beautify XML Strings in Java?

DDD
Release: 2024-12-21 17:01:10
Original
923 people have browsed it

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

}
Copy after login

Usage example:

String unformattedXml = "<tag><nested>hello</nested></tag>";
String formattedXml = XmlBeautifier.formatXml(unformattedXml);
Copy after login

Output Example:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <tag>
    <nested>hello</nested>
  </tag>
</root>
Copy after login

Notes:

  • This approach utilizes XSLT (Extensible Stylesheet Language Transformations) for handling the XML transformation.
  • The output formatting may vary slightly depending on the Java version and the specific XML parsing library used.
  • Alternative libraries, such as XMLSpy or Oxygen XML Editor, provide comprehensive XML formatting capabilities.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template