Skip to content

Convert XML to Java String

Convert XML to Java String example shows how to convert an XML file to Java string. This example also shows using BufferedReader and StringBuilder objects.

How to convert XML to string in Java?

Many times we want to get the XML content stored in a file in the Java string object. For the purpose of this example, I am going to use an XML file that is stored in my local hard drive at “E:/demo.xml”. Here is the content of the XML file.

The first step we need to do is to read the file. Since it is an XML file, we are going to use the BufferedReader object. Once we get the BufferedReader object, we will use the while loop to read all lines of the file one by one. We will also append the lines to a StringBuilder object inside the loop.

Once all lines of the XML files are read, we will convert the StringBuilder to the String object using the toString method.


As you can see from the output, the XML file content is converted to a single line string. There are some tab characters visible in the output, but that is because the original XML has that. You can remove that using the String replaceAll method if you want.

If you want to learn more about the string, please visit the Java String Tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.