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.

Output

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

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *