Home >Java >javaTutorial >How to Pretty Print XML in Java Using XSLT?

How to Pretty Print XML in Java Using XSLT?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-14 22:00:26563browse

How to Pretty Print XML in Java Using XSLT?

Pretty Printing XML in Java

Given a Java String containing unformatted XML, the objective is to transform it into a well-structured XML String with proper line breaks and indentation.

Solution:

  1. Instantiate a Transformer:

    Transformer transformer = TransformerFactory.newInstance().newTransformer();
  2. Set Output Properties:

    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
  3. Create a StreamResult for Output:

    StreamResult result = new StreamResult(new StringWriter());
  4. Create a DOMSource for the Input String:

    DOMSource source = new DOMSource(doc);
  5. Transform Source to Result:

    transformer.transform(source, result);
  6. Retrieve Formatted XML String:

    String xmlString = result.getWriter().toString();

Code Example:

String unformattedXml = "hello";
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String formattedXml = result.getWriter().toString();
System.out.println(formattedXml);

Note: The specific results may vary depending on the Java version used. Modifications might be necessary to cater to specific platforms.

The above is the detailed content of How to Pretty Print XML in Java Using XSLT?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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