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

Sometimes, we may come across a scenario that requires us to convert an XML (Extensible Markup Language) string to an actual XML document that we can process. It’s more common in tasks like web crawling or retrieving XML data stored in a database.

In this tutorial, we’ll discuss how to convert an XML string to an XML document. In particular, we’ll cover two approaches to the problem. Then, we’ll discuss how to parse an XML file into a Java String object.

2. Example XML String and XML File

To illustrate, we use a simple XML document that contains data about blog posts:

<?xml version="1.0" encoding="UTF-8"?>
<posts>
    <post postId="1">
        <title>Parsing XML as a String in Java</title>
        <author>John Doe</author>
    </post>
</posts>

In this case, posts is the root node that contains at least one post as a child, but could hold more post children.

Notably, a simple XML document doesn’t usually need an XML declaration (the first line). However, an XML file (version 1.0) does need an XML declaration as a best practice, and it becomes a requirement for XML 1.1.

3. XMLUnit and Setting up Maven

Comparing XML strings, especially with an XML document parsed from an XML file, often goes beyond a simple expected.equals(actual) test. This is because XML has semantic rules that plain string comparison ignores.

For these reasons, the best practice for comparing XML strings with XML files in Java tests is to use a dedicated XML comparison library like XMLUnit. XMLUnit understands and handles XML semantics and can compare documents while ignoring irrelevant differences.

To integrate XMLUnit with AssertJ, let’s include the AssertJ and XMLUnit dependencies in the pom.xml:

<dependencies>
    <dependency>
        <groupId>org.assertj</groupId>
        <artifactId>assertj-core</artifactId>
        <version>3.26.0</version> 
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.xmlunit</groupId>
        <artifactId>xmlunit-assertj</artifactId>
        <version>2.10.0</version> 
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.xmlunit</groupId>
        <artifactId>xmlunit-core</artifactId>
        <version>2.10.0</version> 
        <scope>test</scope>
    </dependency>
</dependencies>

In this case, we use version 2.10.0 of both.

4. Parsing XML From a String

In this section, we cover two methods to parse XML from an example string.

4.1. InputSource With StringReader

When we parse an XML document, we build an instance of the DocumentBuilder class. Then, we invoke the parse method on the instance, which expects an input source to parse the XML from.

In this case, the XML is a string. However, if we pass the string directly to the parse method, it throws an exception. Specifically, that’s because the parse method expects the string to be a URI (Uniform Resource Identifier) that points to the XML resource.

Instead, we need to create a custom input source for the XML string, e.g., with StringReader:

String xmlString = "<posts>...</posts>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource inputSource = new InputSource(new StringReader(xmlString));
Document document = builder.parse(inputSource);

Let’s break this down:

  • xmlString is the example XML string
  • DocumentBuilder is a helper class that lets us parse and create XML documents
  • InputSource is a wrapper that can consume XML data from various sources such as files, strings, and streams
  • StringReader turns the XML string into a readable stream of characters

Essentially, the InputSource can take a Reader object to parse it as an XML:

public InputSource(Reader characterStream)

Similarly, the parse method takes an InputSource:

public Document parse(InputSource is)

Eventually, the parse method creates an XML document out of the string. We can test it out by passing the example document as a string to it:

@Test
public void givenXmlString_whenConvertToDocument_thenSuccess() {
    ...
    assertNotNull(document);
    assertEquals("posts", document.getDocumentElement().getNodeName());
    Element rootElement = document.getDocumentElement();
    var childElements = rootElement.getElementsByTagName("post");
    assertNotNull(childElements);
    assertEquals(1, childElements.getLength());
}

Of course, we expect the test to pass if the XML string is a valid markup.

4.2. InputStream of Byte Array

InputStream is another common approach to parsing XML. Specifically, InputStream is useful when we need to parse XML from a stream such as a network stream or a file stream. In addition, it’s simpler to use than InputSource, which lets us fine-tune the parsing process.

First, let’s create an instance of ByteArrayInputStream from the XML string. Then, we feed it to the parse method:

InputStream inputStream = new ByteArrayInputStream(xmlString.getBytes(StandardCharsets.UTF_8));
Document document = builder.parse(inputStream);

In the code above, we convert the string to an array of bytes. In addition, we also specify the character encoding, which is UTF-8 in this case.

5. Parsing an XML File Into a String

In this section, we parse an XML file into a single-line XML string and verify that it is indeed the original example string.

5.1. Reading the XML File

To begin with, let’s obtain a FileReader object for the posts.xml file in the resources directory:

String filePath = "posts.xml";
ClassLoader classLoader = getClass().getClassLoader();
FileReader fileReader = new FileReader(classLoader.getResource(filePath).getFile());

Then, we initialize a StringBuilder object:

StringBuilder xmlContentBuilder = new StringBuilder();

Notably, we use a FileReader to read characters from the specified file and wrap the FileReader in a BufferedReader. This is done because a BufferedReader provides efficient reading of characters, arrays, and lines by buffering input. This is generally preferred for reading text files line by line.

Let’s use the try-with-resources statement to ensure that the BufferedReader and, implicitly, the FileReader are automatically closed when the block is exited, even if exceptions occur.

As is common, we use a while statement to read the file line by line:

try (BufferedReader reader = new BufferedReader(fileReader)) {
    String line;
    while ((line = reader.readLine()) != null) {
        xmlContentBuilder.append(line);
    }
}
String xmlString = xmlContentBuilder.toString();

The readLine() returns null when the end of the file is reached. Each line read from the file is appended directly to the StringBuilder. Crucially, readLine() strips the line endings (newline characters) for us. This means when we append(line), we are already concatenating lines without their original line breaks. Once all lines are read, we call toString() on the StringBuilder to get the complete concatenated string.

5.2. Removing Tabs and Extra Spaces From the XML String

XML often contains whitespace characters that aren’t usually important to us once we’ve read it into memory. So, let’s clean those up with some regular expression replacements. Notably, we only remove insignificant whitespace as opposed to significant whitespace.

First, let’s remove all tab characters:

xmlString = xmlString.replaceAll("\\t", "");

Then, we replace multiple spaces with a single space:

xmlString = xmlString.replaceAll(" +", " ");

To ensure truly minimal whitespace, let’s use a regular expression to remove whitespace between XML tags (e.g., “> <“):

xmlString = xmlString.replaceAll(">\\s+<", "><");

Finally, we trim leading and trailing whitespace from the entire string:

String oneLineXml = xmlString.trim();

The result should be a one-line XML string that we have created after parsing the XML file and removing extra white space; however, it includes the XML declaration.

5.3. Testing With AssertJ

To test, let’s use the XmlAssert method assertThat(actualXml).and(expectedXml).areIdentical() method. It performs a strict comparison, meaning whitespace, attribute order, and element order must all match.

It’s like a plain string equals() but for XML:

@Test
public void givenXmlFile_whenConvertToOneLineString_thenSuccess() throws IOException {
       
    String filePath = "posts.xml";
    ClassLoader classLoader = getClass().getClassLoader();
    FileReader fileReader = new FileReader(classLoader
      .getResource(filePath)
      .getFile());
    StringBuilder xmlContentBuilder = new StringBuilder();
    try (BufferedReader reader = new BufferedReader(fileReader)) {
        String line;
        while ((line = reader.readLine()) != null) {
            xmlContentBuilder.append(line);
        }
    }
    String xmlString = xmlContentBuilder.toString();
    xmlString = xmlString.replaceAll("\\t", "");
    xmlString = xmlString.replaceAll(" +", " ");
    xmlString = xmlString.replaceAll(">\\s+<");
    String oneLineXml = xmlString.trim();
    String expectedXml = """
            <?xml version="1.0" encoding="UTF-8"?><posts><post postId="1"><title>Parsing XML as a String in Java</title><author>John Doe</author></post></posts>
            """;
        
    assertThat(oneLineXml).and(expectedXml).areIdentical();
}

This way, we can ensure that the parsing algorithm produces the expected output.

6. Conclusion

In this article, we reviewed two of the most common approaches to converting an XML string to an XML document in Java.

Specifically, we converted an XML string to a character stream and parsed it as an input source. Similarly, we covered how to parse the string as an input byte array stream. Lastly, we also parsed an XML document from an XML file and converted it into a single-line XML string.

As always, all the code for these examples is available over on GitHub.

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)