String to XML and XML to String in Java

This article provides utility methods to :

  • Convert an xml document object to string
  • Convert a string to xml document object

 
string to xml

 

Convert xml document object to string

For converting xml document to string, we will use DOMSource and Transformer classes as follows :
 

  private static String toXmlString(Document document) throws TransformerException {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(document);
    StringWriter strWriter = new StringWriter();
    StreamResult result = new StreamResult(strWriter);
  
    transformer.transform(source, result);
    
    return strWriter.getBuffer().toString();
    
  }

 

Convert string to xml

For converting the string to xml document, we can use DocumentBuilderFactory and DocumentBuilder classes.

Here is the code for toXmlDocument() method :
 

  private static Document toXmlDocument(String str) throws ParserConfigurationException, SAXException, IOException{
    
     DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
     DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
     Document document = docBuilder.parse(new InputSource(new StringReader(str)));
    
     return document;
  }

 

Complete program

For this program, we can either hardcode the xml string as shown below :
 

    String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"+
            "<Tutorial id=\"1\"><technology>Dot net, Java, Big data, Database</technology>\n"+
            "<address>topjavatutorial.com</address></Tutorial>";

 
or, we can create a sample xml file in the local path and read that.

We have created xml file with name Sample.xml in path C:\tempxml

So, in the main() method, we can use hardcoding as explained above or read this xml file using utility methods.

Here is how the main method will look like :
 

  public static void main(String[] args) {
    
    try{
    //Read an xml from a local path
    String xmlStr = new Scanner( new File("c:/tempxml/Sample.xml") ).useDelimiter("\\Z").next();
    
    //You can also hardcode the xml string.. commenting this since we are reading the file itself
    //String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"+
        //        "<Tutorial id=\"1\"><technology>Dot net, Java, Big data, Database</technology>\n"+
        //        "<address>topjavatutorial.com</address></Tutorial>";
    
    System.out.println("Sample.xml contents = "+ xmlStr);
    
    Document doc = toXmlDocument(xmlStr);
    
    System.out.println("XML document formed");
    
    String str = toXmlString(doc);
    
    System.out.println("Result of xml to string conversion: " + str);
    }
    catch(Exception e ){
      e.printStackTrace();
    }

  }

Running this program creates the following output :


  Sample.xml contents = <?xml version="1.0" encoding="UTF-8"?>
  <Tutorial>
  <technology>Dot net, Java, Big data, Database</technology>
  <address>topjavatutorial.com</address>
  </Tutorial>
  XML document formed
  Result of xml to string conversion: <?xml version="1.0" encoding="UTF-8"?><Tutorial>
  <technology>Dot net, Java, Big data, Database</technology>
  <address>topjavatutorial.com</address>
  </Tutorial>

 

You may also like

 

© 2015 – 2018, https:. All rights reserved. On republishing this post, you must provide link to original post

One comment

  1. […] Convert String to XML and vice versa in java […]

Leave a Reply.. code can be added in <code> </code> tags

%d bloggers like this: