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

XML (eXtensible Markup Language) is one of the most popular schemas for structuring information. Moreover, the parsing and manipulation of XML Documents in Java are commonly accomplished using technologies like DOM (Document Object Model) and SAX (Simple API for XML).

In some cases, it might be necessary to transform an XML Document object into its string form, which could be used to store the XML information inside a database or to pass through over a network.

In this tutorial, we’ll discuss several ways of transforming an XML Document object into a string in Java.

2. Example

Suppose we have the following Document object:

Document document = // ...

This Document object represents XML content in memory:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
    <child1>This is child element 1</child1>
    <child2>This is child element 2</child2>
</root>

Now, we need to convert this XML Document object into a Java string.

3. Using XML Transformation APIs

The javax.xml.transform package in Java includes classes and interfaces for performing XML transformations. One of its capabilities is the conversion of an XML Document object into a string representation. The following code demonstrates how to use the javax.xml.transform package to parse this XML Document object to a Java string:

@Test
public void givenXMLDocument_whenUsingTransformer_thenConvertXMLToString()
throws TransformerException {  
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    StringWriter stringWriter = new StringWriter();
    transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
    String result = stringWriter.toString();

    assertTrue(result.contains("<root>"));
    assertTrue(result.contains("This is child element 1"));
    assertTrue(result.contains("This is child element 2"));
}

We first instantiate a TransformerFactory and a Transformer, used for XML transformation. Then, we construct a StringWriter to store the transformed XML in text form. Then, the transform() method changes the XML Document, and we can save it into the result string using the stringWrite.toString() method.

4. Using Java XMLBeans

Converting between XML Document and string is easy and flexible using the XmlBeans approach in the Java XML manipulation world. We use XmlObject.Factory.parse(document), which parses the XML Document into an XmlObject for subsequent operative activities:

@Test
public void givenXMLDocument_whenUsingXmlBeans_thenConvertXMLToString() {
    try {
        XmlObject xmlObject = XmlObject.Factory.parse(document);

        XmlOptions options = new XmlOptions();
        options.setSavePrettyPrint();
        options.setUseDefaultNamespace();
        options.setSaveAggressiveNamespaces();

        String xmlString = xmlObject.xmlText(options);

        xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" + xmlString;

        assertTrue(xmlString.contains("<root>"));
        assertTrue(xmlString.contains("This is child element 1"));
        assertTrue(xmlString.contains("This is child element 2"));
    } catch (XmlException e) {
        e.printStackTrace();
    }
}

In the above test method, we parse the document into an XmlObject using XmlOptions to customize output formatting such as pretty-printing, namespaces, etc. Moreover, asserts are done to establish that a resulting XML string contains an XML declaration and particular XML elements and element contents.

5. Conclusion

In this tutorial, we discuss how to convert an XML Document object to a string in Java.

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