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

How to Pretty Print XML in Java Using XSLT?

Patricia Arquette
Release: 2024-12-14 22:00:26
Original
494 people have browsed it

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();
    Copy after login
  2. Set Output Properties:

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

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

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

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

    String xmlString = result.getWriter().toString();
    Copy after login

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);
Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template