Saturday, 24 March 2018

Convert xml document to string

In this post, I am going to show, how can you convert an xml document to plain string.

Approach1: Using StringBuilder

Approach2: Using javax.xml package

I am going to use ‘books.xml’ file to demonstrate the examples.

books.xml
<?xml version="1.0"?>
<!-- Represents Books information in store -->
<books>
 <book id="1">
  <name>Let Us C</name>
  <author>Yashwant Kanetkar</author>
  <price>245.00</price>  
 </book>
 <book id="2">
  <name>Let Us C++</name>
  <author>Yashwant Kanetkar</author>
  <price>252.00</price>  
 </book>
 <book id="3">
  <name>Java The Complete Reference</name>
  <author>Herbert Schildt</author>
  <price>489.00</price>  
 </book>
 <book id="4">
  <name>HTML5 Black Book</name>
  <author>Kogent Learning Solutions</author>
  <price>485.00</price>  
 </book> 
</books>

Approach 1: Using StringBuilder
Below statements convert the xml file to string in java.

BufferedReader br = new BufferedReader(new FileReader(new File(xmlFilePath)));
String line;
StringBuilder sb = new StringBuilder();

while ((line = br.readLine()) != null) {
         sb.append(line.trim());
}

Find the below working application.

XMLUtil.java
package com.sample.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class XMLUtil {

 public static String getXMLString(String xmlFilePath) {
  if (xmlFilePath == null || xmlFilePath.isEmpty()) {
   throw new IllegalArgumentException("xmlFilePath can't be null or empty");
  }

  try (BufferedReader br = new BufferedReader(new FileReader(new File(xmlFilePath)))) {
   String line;
   StringBuilder sb = new StringBuilder();

   while ((line = br.readLine()) != null) {
    sb.append(line.trim());
   }

   return sb.toString();
  } catch (IOException e) {
   throw new RuntimeException(e);
  }

 }
}

Test.java
package com.sample.util;

import java.io.IOException;

public class Test {

 public static void main(String args[]) throws IOException {
  String xmlFilePath = "C:\\Users\\krishna\\books.xml";
  
  String xmlStr = XMLUtil.getXMLString(xmlFilePath);
  
  System.out.println(xmlStr);
 }
}


Output
xml : <?xml version="1.0"?><!-- Represents Books information in store --><books><book id="1"><name>Let Us C</name><author>Yashwant Kanetkar</author><price>245.00</price></book><book id="2"><name>Let Us C++</name><author>Yashwant Kanetkar</author><price>252.00</price></book><book id="3"><name>Java The Complete Reference</name><author>Herbert Schildt</author><price>489.00</price></book><book id="4"><name>HTML5 Black Book</name><author>Kogent Learning Solutions</author><price>485.00</price></book></books>

Approach2: Using javax.xml package


XMLUtil.java
package com.sample.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

public class XMLUtil {

 public static String getXMLString(String xmlFilePath) {
  if (xmlFilePath == null || xmlFilePath.isEmpty()) {
   throw new IllegalArgumentException("xmlFilePath can't be null or empty");
  }
  DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

  try (InputStream iStream = new FileInputStream(new File(xmlFilePath))) {
   Document document = documentBuilderFactory.newDocumentBuilder().parse(iStream);

   StringWriter stringWriter = new StringWriter();

   Transformer transformer = TransformerFactory.newInstance().newTransformer();

   transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");

   transformer.transform(new DOMSource(document), new StreamResult(stringWriter));

   String output = stringWriter.toString();

   String result = output.replaceAll("\n|\r", "");

   return result;
  } catch (Exception e) {
   throw new RuntimeException(e);
  }

 }
}

Test.java
package com.sample.util;

import java.io.IOException;

public class Test {

 public static void main(String args[]) throws IOException {
  String xmlFilePath = "C:\\Users\\krishna\\books.xml";
  
  String xmlStr = XMLUtil.getXMLString(xmlFilePath);
  
  System.out.println(xmlStr);
 }
}

Output
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!-- Represents Books information in store --><books> <book id="1">  <name>Let Us C</name>  <author>Yashwant Kanetkar</author>  <price>245.00</price>   </book> <book id="2">  <name>Let Us C++</name>  <author>Yashwant Kanetkar</author>  <price>252.00</price>   </book> <book id="3">  <name>Java The Complete Reference</name>  <author>Herbert Schildt</author>  <price>489.00</price>   </book> <book id="4">  <name>HTML5 Black Book</name>  <author>Kogent Learning Solutions</author>  <price>485.00</price>   </book> </books>

Use below statement, to remove all the spaces.
String result = output.replaceAll("\n|\r|\\s+", "");


In my next post, I am going to show you how to convert a string to xml document.

You may like




No comments:

Post a Comment