Pages

Thursday, June 5, 2014

Creating an XML Document node from XML string

Following method helps you convert XML String into a XML Document Object

 

import java.io.ByteArrayInputStream;

import java.io.InputStream;

 

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

 

import org.w3c.dom.Document;

      

public Document getXMLDoc(String xmlString) {

       InputStream is = new ByteArrayInputStream(xmlString.getBytes());

       DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

       DocumentBuilder dBuilder = null;

       Document doc = null;

       try {

              dBuilder = dbFactory.newDocumentBuilder();

              doc = dBuilder.parse(is);

       } catch (Exception e) {

              // TODO Auto-generated catch block

              // logger.error("Parsing exception iha xml traversal");

       }

      

       return doc;

}

      

You can use the doc object as follows

 

doc.getElementsByTagName(tagName)

 

 

No comments:

Post a Comment