Parse xml data to java pojo using DOM


Parse xml data to java pojo using DOM

Parse xml data to java pojo using DOM is an important aspect in java programming so let’s understand how to Parse xml data to java pojo using DOM. Here we will parse XML data and we will set parsed data into java class object.

Here i am taking one student.xml file StudentInfo POJO class and one main class to parse XML data.

student.xml

<?xml version="1.0" encoding="UTF-8"?>
<student>
 <roll>101</roll>
 <name>Vikash</name>
 <address>Hyderabad</address>
</student>

StudentInfo.java

package com.javagf.resource;

public class StudentInfo {

 private int roll;
 private String name;
 private String address;

 public int getRoll() {
 return roll;
 }

 public void setRoll(int roll) {
 this.roll = roll;
 }

 public String getName() {
 return name;
 }

 public void setName(String name) {
 this.name = name;
 }

 public String getAddress() {
 return address;
 }

 public void setAddress(String address) {
 this.address = address;
 }

 @Override
 public String toString() {
 return "StudentInfo [roll=" + roll + ", name=" + name + ", address=" + address + "]";
 }

}

DOMParser.java

package com.javagf.resource;

import java.io.IOException;

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

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

public class DOMParser {
 public static final String FILE_NAME = "D:\\REST\\AllMethod\\XML\\student.xml";

 public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {

   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
   DocumentBuilder builder = factory.newDocumentBuilder();
   Document document = builder.parse(FILE_NAME);

   // Go to the Roll element
    NodeList nodeList = document.getFirstChild().getChildNodes();
    StudentInfo studentInfo = null;
    studentInfo = new StudentInfo();
    // Read element one by one
    for (int i = 0; i < nodeList.getLength(); i++) {
       Node node = nodeList.item(i);
       if (node.getNodeType() == Node.ELEMENT_NODE) {
         // get xml element name
          String name = node.getNodeName();
         // get xml element value
         String value = node.getTextContent();
            if (name.equals("roll")) {
               studentInfo.setRoll(Integer.parseInt(value));
            } else if (name.equals("name")) {
               studentInfo.setName(value);
            } else if (name.equals("address")) {
              studentInfo.setAddress(value);
        }
    }
 }
     System.out.println(studentInfo);
 }

}

Output

StudentInfo [roll=101, name=Vikash, address=Hyderabad]






Full-stack web and mobile app development company Contact Us : Skype: indore.webcoder Email: info@w3sparks.com Sales: +91 8085506229