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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?xml version="1.0"?> <books> <book id="1"> <title>Java Complete Reference</title> <genre>Computer</genre> <price>700</price> <publish_date>2020-10-01</publish_date> </book> <book id="2"> <title>Java Cookbook</title> <genre>Computer</genre> <price>950</price> <publish_date>2020-12-5</publish_date> </book> </books> |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
package com.javacodeexamples.stringexamples; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; public class XMLToString { public static void main(String[] args) { String strXMLFilePath = "E:/demo.xml"; String strXML = getXMLAsString(strXMLFilePath); System.out.println(strXML); } private static String getXMLAsString(String strXMLFilePath) { StringBuilder sb = new StringBuilder(); BufferedReader reader = null; try { //create buffered reader reader = new BufferedReader(new FileReader(new File(strXMLFilePath))); //read xml line by line String strLine; while( (strLine = reader.readLine()) != null ) { //append to string builder object sb.append(strLine); } }catch(Exception e) { e.printStackTrace(); }finally { try { if( reader != null ) reader.close(); }catch(Exception e) {} } //convert to string return sb.toString(); } } |
Output
1 |
<?xml version="1.0"?><books><book id="1"> <title>Java Complete Reference</title> <genre>Computer</genre> <price>700</price> <publish_date>2000-10-01</publish_date></book><book id="2"> <title>Java Cookbook</title> <genre>Computer</genre> <price>950</price> <publish_date>2000-12-16</publish_date></book></books> |
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.