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 – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Introduction

One of the most common data formats today is XML (Extensible Markup Language), which is widely used in structuring and exchanging data between applications.

Moreover, this use case is common in Java, where we must change some pieces of XML markup text to org.w3c.dom.Document object.

In this tutorial, we’ll discuss converting a string with XML-based content into Org.w3c.dom.Document in Java.

2. org.w3c.dom.Document

The org.w3c.dom.Document is an integral component of the Document Object Model (DOM) XML API in Java. This essential class represents an entire XML document and provides a comprehensive set of methods for navigating, modifying, and retrieving data from XML documents. When working with XML in Java, the org.w3c.dom.Document object becomes an indispensable tool.

To better understand how to create an org.w3c.dom.Document object, let’s look at the following example:

try {
    // Create a DocumentBuilderFactory
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    // Create a DocumentBuilder
    DocumentBuilder builder = factory.newDocumentBuilder();

    // Create a new Document
    Document document = builder.newDocument();

    // Create an example XML structure
    Element rootElement = document.createElement("root");
    document.appendChild(rootElement);

    Element element = document.createElement("element");
    element.appendChild(document.createTextNode("XML Document Example"));
    rootElement.appendChild(element);
    
} catch (ParserConfigurationException e) {
    e.printStackTrace();
}

In the previous code, we start by creating the necessary elements for the parsing of XML, such as DocumentBuilderFactory and DocumentBuilder. After that, it builds a basic XML schema with an initial node element labeled “root” encompassing another child node element referred to as “element” that has the string “XML document example”. Moreover, the XML output should be as follows:

<root>
    <element>XML Document Example</element>
</root>

3. Parsing XML from a String

Parsing of the XML string is needed for converting the string containing XML into an org.w3c.dom.Document. Fortunately, there are several XML parsing libraries in Java, which include DOM, SAX, and StAX.

This article takes it easy by concentrating on the DOM parser for a simple explanation. Let’s walk through a step-by-step example of how to parse a string with XML and create an org.w3c.dom.Document object:

@Test
public void givenValidXMLString_whenParsing_thenDocumentIsCorrect()
  throws ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    String xmlString = "<root><element>XML Parsing Example</element></root>";
    InputSource is = new InputSource(new StringReader(xmlString));
    Document xmlDoc = null;
    try {
        xmlDoc = builder.parse(is);
    } catch (SAXException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    assertEquals("root", xmlDoc.getDocumentElement().getNodeName());
    assertEquals("element", xmlDoc.getDocumentElement().getElementsByTagName("element").item(0).getNodeName());
    assertEquals("XML Parsing Example",
      xmlDoc.getDocumentElement().getElementsByTagName("element").item(0).getTextContent());
}

In the above code, we create a DocumentBuilderFactory and DocumentBuilder that are critical for XML parsing. Additionally, we define a sample XML string (xmlString) that is converted into an InputSource for parsing. We parse XML within a try-catch block and catch any possible exception like SAXException or IOException.

Finally, we employ a series of assertions to verify the correctness of the parsed XML document, including checks for the root element’s name using getDocumentElement().getNodeName(), the child element’s name using getDocumentElement().getElementsByTagName(), and the text content within the child element.

4. Conclusion

In conclusion, for any competent Java developer who deals with XML-based data in numerous applications, from data processing to web services or configurational tasks, it is vital to know how to operate org.w3c.dom.Document (NS).

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.
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.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW