Sunday, 19 January 2020

Parse XML String in Java


We can parse xml string by getting a Document object.
public static Document loadXMLFromString(String xml) throws Exception {
 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 DocumentBuilder documentBuilder = factory.newDocumentBuilder();
 InputSource inputStream = new InputSource(new StringReader(xml));
 return documentBuilder.parse(inputStream);
}


App.java
package com.sample.app;

import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class App {

 public static Document loadXMLFromString(String xml) throws Exception {
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  DocumentBuilder documentBuilder = factory.newDocumentBuilder();
  InputSource inputStream = new InputSource(new StringReader(xml));
  return documentBuilder.parse(inputStream);
 }

 public static void main(String[] args) throws Exception {
  String xml = "<employee>\n" + " <firstName>Krishna</firstName>\n" + " <lastName>Gurram</lastName>\n"
    + "</employee>";

  Document document = loadXMLFromString(xml);

  NodeList nodeList = document.getChildNodes();

  Node employeeNode = nodeList.item(0);
  NodeList employeeChildNodes = employeeNode.getChildNodes();

  System.out.println("Child nodes of '" + employeeNode.getNodeName() + "' node are : ");
  for (int i = 0; i < employeeChildNodes.getLength(); i++) {
   System.out.println(employeeChildNodes.item(i).getNodeName());
  }

 }

}


Output
Child nodes of 'employee' node are : 
#text
firstName
#text
lastName
#text


You may like

No comments:

Post a Comment