Last Updated:

How to convert a string to an XML Document. Creating a String from Document

From String to XML Document and vice versa

Programming in Java often has to deal with strings that contain XML markup. Such objects need to be processed somehow. To do this, we need to transform (convert) such a string c XML into a Document object (). A similar conversion task occurs during debugging, when we need to convert an XML Document to a String

In this article, we figured out how to make a beautiful and readable output of an unformatted string with XML markup. In this article, we're more interested in the correct way to convert between a String and a Document object.

Converting to String from xml Document and vice versa using an example

Let's write 2 methods for converting and converting XML and String back:

  • The method takes a string of XML markup as input, and then parses it and returns it as a Document DOM. We're going to use that as well.stringToDocument(String xmlString)InputSourceStringReader
  • The method takes a Document as input and converts it to a String object. To do this, you use the , and .documentToString(Document document)TransformerStringWriterStreamResultjavax.xml.transform

Let's write the DocumentToStringConverter class and implement these methods:

Now let's run our program and look at the console:

As you can see, the input string was recognized correctly, converted to an XML Document, and then converted back to a String object.