eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

When we need to read an XML file manually, usually, we would like to read the content in a pretty-printed format. Many text editors or IDEs can reformat XML documents. If we work in Linux, we can pretty-print XML files from the command line.

However, sometimes, we have requirements to convert a raw XML string to the pretty-printed format in our Java program. For example, we may want to show a pretty-printed XML document in the user interface for better visual comprehension.

In this tutorial, we’ll explore how to pretty-print XML in Java.

2. Introduction to the Problem

For simplicity, we’ll take a non-formatted emails.xml file as the input:

<emails> <email> <from>Kai</from> <to>Amanda</to> <time>2018-03-05</time>
<subject>I am flying to you</subject></email> <email>
<from>Jerry</from> <to>Tom</to> <time>1992-08-08</time> <subject>Hey Tom, catch me if you can!</subject>
</email> </emails>

As we can see, the emails.xml file is well-formed. However, it’s not easy to read due to the messy format.

Our goal is to create a method to convert this ugly, raw XML string to a pretty-formatted string.

Further, we’ll discuss customizing two common output properties: indent-size (integer) and suppressing XML declaration (boolean).

The indent-size property is pretty straightforward: It’s the number of spaces to indent (per level). On the other hand, the suppressing XML declaration option decides if we want to have the XML declaration tag in the generated XML. A typical XML declaration looks like:

<?xml version="1.0" encoding="UTF-8"?>

In this tutorial, we’ll address a solution with the standard Java API and another approach using an external library.

Next, let’s see them in action.

3. Pretty-Printing XML With the Transformer Class

Java API provides the Transformer class to do XML transformations.

3.1. Using the Default Transformer

First, let’s see the pretty-print solution using the Transformer class:

public static String prettyPrintByTransformer(String xmlString, int indent, boolean ignoreDeclaration) {

    try {
        InputSource src = new InputSource(new StringReader(xmlString));
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, ignoreDeclaration ? "yes" : "no");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        Writer out = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(out));
        return out.toString();
    } catch (Exception e) {
        throw new RuntimeException("Error occurs when pretty-printing xml:\n" + xmlString, e);
    }
}

Now, let’s walk through the method quickly and figure out how it works:

  • First, we parse the raw XML string and get a Document object.
  • Next, we obtain a TransformerFactory instance and set the required indent-size attribute.
  • Then, we can get a default transformer instance from the configured tranformerFactory object.
  • The transformer object supports various output properties. To decide if we want to skip the declaration, we set the OutputKeys.OMIT_XML_DECLARATION attribute.
  • Since we would like to have a pretty-formatted String object, finally, we transform() the parsed XML Document to a StringWriter and return the transformed String.

We’ve set the indent size on the TransformerFactory object in the method above. Alternatively, we can also define the indent-amount property on the transformer instance:

transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent));

Next, let’s test if the method works as expected.

3.2. Testing the Method

Our Java project is a Maven project, and we’ve put the emails.xml under src/main/resources/xml/email.xml. We’ve created the readFromInputStream method to read the input file as a String. But, we won’t go into the details of this method since it doesn’t have much to do with our topic here. Let’s say we want to set the indent-size=2 and skip the XML declaration in the result:

public static void main(String[] args) throws IOException {
    InputStream inputStream = XmlPrettyPrinter.class.getResourceAsStream("/xml/emails.xml");
    String xmlString = readFromInputStream(inputStream);
    System.out.println("Pretty printing by Transformer");
    System.out.println("=============================================");
    System.out.println(prettyPrintByTransformer(xmlString, 2, true));
}

As the main method shows, we read the input file as a String and then call our prettyPrintByTransformer method to get a pretty-printed XML String.

Next, let’s run the main method with Java 8:

Pretty printing by Transformer
=============================================
<emails>
  <email>
    <from>Kai</from>
    <to>Amanda</to>
    <time>2018-03-05</time>
    <subject>I am flying to you</subject>
  </email>
  <email>
    <from>Jerry</from>
    <to>Tom</to>
    <time>1992-08-08</time>
    <subject>Hey Tom, catch me if you can!</subject>
  </email>
</emails>

As the output above shows, our method works as expected.

However, if we test it once again with Java 9 or a later version, we may see different output.

Next, let’s see what it produces if we run it with Java 9:

Pretty printing by Transformer
=============================================
<emails>
   
  <email>
     
    <from>Kai</from>
     
    <to>Amanda</to>
     
    <time>2018-03-05</time>
    
    <subject>I am flying to you</subject>
  </email>
   
  <email>
    
    <from>Jerry</from>
     
    <to>Tom</to>
     
    <time>1992-08-08</time>
     
    <subject>Hey Tom, catch me if you can!</subject>
    
  </email>
   
</emails>

=============================================

As we can see in the output above, there are unexpected empty lines in the output.

This is because our raw input contains whitespace between elements, for example:

<emails> <email> <from>Kai</from> ...

As of Java 9, the Transformer class’s pretty-print feature doesn’t define the actual format. Therefore, whitespace-only nodes will be outputted as well. This has been discussed in this JDK bug ticket. Also, Java 9’s release note has explained this in the xml/jaxp section.

If we want our pretty-print method to always generate the same format under various Java versions, we need to provide a stylesheet file.

Next, let’s create a simple xsl file to achieve that.

3.3. Providing an XSLT File

First, let’s create the prettyprint.xsl file to define the output format:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:strip-space elements="*"/>
    <xsl:output method="xml" encoding="UTF-8"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

As we can see, in the prettyprint.xsl file, we’ve used the <xsl:strip-space/> element to remove whitespace-only nodes so that they do not appear in the output.

Next, we still need to make a small change to our method. We won’t use the default transformer anymore. Instead, we’ll create a Transformer object with our XSLT document:

Transformer transformer = transformerFactory.newTransformer(new StreamSource(new StringReader(readPrettyPrintXslt())));

Here, the readPrettyPrintXslt() method reads prettyprint.xsl content.

Now, if we test the method in Java 8 and Java 9, both produce the same output:

Pretty printing by Transformer
=============================================
<emails>
  <email>
    <from>Kai</from>
    <to>Amanda</to>
    <time>2018-03-05</time>
    <subject>I am flying to you</subject>
  </email>
...
</emails>

We’ve solved the problem with the standard Java API. Next, let’s pretty print the emails.xml using an external library.

4. Pretty-Printing XML With the Dom4j Library

Dom4j is a popular XML library. It allows us to easily pretty-print XML documents.

First, let’s add the Dom4j dependency into our pom.xml:

<dependency>
    <groupId>org.dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>2.1.3</version>
</dependency>

We’ve used the 2.1.3 version as an example. We can find the latest version in the Maven Central repository.

Next, let’s see how to pretty-print XML using the Dom4j library:

public static String prettyPrintByDom4j(String xmlString, int indent, boolean skipDeclaration) {
    try {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setIndentSize(indent);
        format.setSuppressDeclaration(skipDeclaration);
        format.setEncoding("UTF-8");

        org.dom4j.Document document = DocumentHelper.parseText(xmlString);
        StringWriter sw = new StringWriter();
        XMLWriter writer = new XMLWriter(sw, format);
        writer.write(document);
        return sw.toString();
    } catch (Exception e) {
        throw new RuntimeException("Error occurs when pretty-printing xml:\n" + xmlString, e);
    }
}

D0m4j’s OutputFormat class has provided a createPrettyPrint method to create a pre-defined pretty-print OutputFormat object. As the method above shows, we can add some customizations on the default pretty-print format. In this case, we set the indent size and decide if we would like to include the declaration in the result.

Next, we parse the raw XML string and create an XMLWritter object with the prepared OutputFormat instance.

Finally, the XMLWriter object will write the parsed XML document in the required format.

Next, let’s test if it can pretty-print the emails.xml file. This time, let’s say we would like to include the declaration and have an indent size of 8 in the result:

System.out.println("Pretty printing by Dom4j");
System.out.println("=============================================");
System.out.println(prettyPrintByDom4j(xmlString, 8, false));

When we run the method, we’ll see the output:

Pretty printing by Dom4j
=============================================
<?xml version="1.0" encoding="UTF-8"?>

<emails> 
        <email> 
                <from>Kai</from>  
                <to>Amanda</to>  
                <time>2018-03-05</time>  
                <subject>I am flying to you</subject>
        </email>  
        <email> 
                <from>Jerry</from>  
                <to>Tom</to>  
                <time>1992-08-08</time>  
                <subject>Hey Tom, catch me if you can!</subject> 
        </email> 
</emails>

As the output above shows, the method has solved the problem.

5. Conclusion

In this article, we’ve addressed two approaches to pretty-print an XML file in Java.

We can pretty-print XMLs using the standard Java API. However, we need to keep in mind the Transformer object may produce different results depending on the Java version. The solution is to provide an XSLT file.

Alternatively, the Dom4j library can solve the problem straightforwardly.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)