Java & Xml tutorial (II) parse XML files using DOM

Source: Internet
Author: User
The DOMXML Parsing method is the easiest to understand. it reads XML files into the memory as Document objects, and then you can easily traverse different elements and node objects. You do not need to traverse elements and nodes in order.


Dom xml parsing is the easiest way to understand. it reads XML files into the memory as Document objects, and then you can easily traverse different elements and node objects. You do not need to traverse elements and nodes in order.
DOM parsing is suitable for small XML files. because it loads all the XML files into the memory for processing, it is not suitable for processing large XML files. For large XML files, you must use SAX for parsing.
In this tutorial, we will read and parse XML files and use them to create objects. The following is the XML file to be parsed.
Employee. xml

 
     
          
   
    Pankaj
           29        
   
    Java Developer
           
   
    Male
       
      
          
   
    Lisa
           35        
   
    CSS Developer
           
   
    Female
       
  
 

The content of this XML file is a list of Employee information. Therefore, we need to create an Employee class to indicate the Employee, and then read the XML file information to the program.
The following is the definition of the Employee class:

package com.journaldev.xml;public class Employee {    private String name;        private String gender;        private int age;        private String role;        public String getName() {            return name;    }    public void setName(String name) {        this.name = name;    }    public String getGender() {        return gender;    }    public void setGender(String gender) {        this.gender = gender;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public String getRole() {        return role;    }    public void setRole(String role) {        this.role = role;    }    @Override    public String toString() {            return "Employee:: Name=" + this.name + " Age=" + this.age + " Gender=" + this.gender +                    " Role=" + this.role;    }}

Note that here I overwrite the toString () method to print useful information about employee objects. Next, we use DOM parsing in the program to read the XML file to obtain the list of Employee objects.
XMLReaderDOM. java

package com.journaldev.xml;import java.io.File;import java.io.IOException;import java.util.ArrayList;import java.util.List;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;public class XMLReaderDOM {    public static void main(String[] args) {        String filePath = "employee.xml";        File xmlFile = new File(filePath);        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();        DocumentBuilder dBuilder;        try {            dBuilder = dbFactory.newDocumentBuilder();            Document doc = dBuilder.parse(xmlFile);            doc.getDocumentElement().normalize();            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());            NodeList nodeList = doc.getElementsByTagName("Employee");            //now XML is loaded as Document in memory, lets convert it to Object List            List
 
   empList = new ArrayList
  
   ();            for (int i = 0; i < nodeList.getLength(); i++) {                empList.add(getEmployee(nodeList.item(i)));            }            //lets print Employee list information            for (Employee emp : empList) {                System.out.println(emp.toString());            }        } catch (SAXException | ParserConfigurationException | IOException e1) {            e1.printStackTrace();        }    }    private static Employee getEmployee(Node node) {        //XMLReaderDOM domReader = new XMLReaderDOM();        Employee emp = new Employee();        if (node.getNodeType() == Node.ELEMENT_NODE) {            Element element = (Element) node;            emp.setName(getTagValue("name", element));            emp.setAge(Integer.parseInt(getTagValue("age", element)));            emp.setGender(getTagValue("gender", element));            emp.setRole(getTagValue("role", element));        }        return emp;    }    private static String getTagValue(String tag, Element element) {        NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();        Node node = (Node) nodeList.item(0);        return node.getNodeValue();    }}
  
 

The program output content is as follows:

Root element :EmployeesEmployee:: Name=Pankaj Age=29 Gender=Male Role=Java DeveloperEmployee:: Name=Lisa Age=35 Gender=Female Role=CSS Developer

In actual situations, we need to verify the validity of the XML file before parsing the XML file, and learn how to use XSD to verify the XML file.

Original article address :#

Dom xml parsing is the easiest way to understand. it reads XML files into the memory as Document objects, and then you can easily traverse different elements and node objects. You do not need to traverse elements and nodes in order.
DOM parsing is suitable for small XML files. because it loads all the XML files into the memory for processing, it is not suitable for processing large XML files. For large XML files, you must use SAX for parsing.
In this tutorial, we will read and parse XML files and use them to create objects. The following is the XML file to be parsed.
Employee. xml

 
     
          
   
    Pankaj
           29        
   
    Java Developer
           
   
    Male
       
      
          
   
    Lisa
           35        
   
    CSS Developer
           
   
    Female
       
  
 

The content of this XML file is a list of Employee information. Therefore, we need to create an Employee class to indicate the Employee, and then read the XML file information to the program.
The following is the definition of the Employee class:

package com.journaldev.xml;public class Employee {    private String name;        private String gender;        private int age;        private String role;        public String getName() {            return name;    }    public void setName(String name) {            this.name = name;    }    public String getGender() {            return gender;    }    public void setGender(String gender) {            this.gender = gender;    }    public int getAge() {            return age;    }    public void setAge(int age) {            this.age = age;    }    public String getRole() {            return role;    }    public void setRole(String role) {            this.role = role;    }    @Override    public String toString() {            return "Employee:: Name=" + this.name + " Age=" + this.age + " Gender=" + this.gender +                    " Role=" + this.role;    }}

Note that here I overwrite the toString () method to print useful information about employee objects. Next, we use DOM parsing in the program to read the XML file to obtain the list of Employee objects.
XMLReaderDOM. java

package com.journaldev.xml;import java.io.File;import java.io.IOException;import java.util.ArrayList;import java.util.List;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;public class XMLReaderDOM {    public static void main(String[] args) {        String filePath = "employee.xml";        File xmlFile = new File(filePath);        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();        DocumentBuilder dBuilder;        try {            dBuilder = dbFactory.newDocumentBuilder();            Document doc = dBuilder.parse(xmlFile);            doc.getDocumentElement().normalize();            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());            NodeList nodeList = doc.getElementsByTagName("Employee");            //now XML is loaded as Document in memory, lets convert it to Object List            List
 
   empList = new ArrayList
  
   ();            for (int i = 0; i < nodeList.getLength(); i++) {                empList.add(getEmployee(nodeList.item(i)));            }            //lets print Employee list information            for (Employee emp : empList) {                System.out.println(emp.toString());            }        } catch (SAXException | ParserConfigurationException | IOException e1) {            e1.printStackTrace();        }    }    private static Employee getEmployee(Node node) {        //XMLReaderDOM domReader = new XMLReaderDOM();        Employee emp = new Employee();        if (node.getNodeType() == Node.ELEMENT_NODE) {            Element element = (Element) node;            emp.setName(getTagValue("name", element));            emp.setAge(Integer.parseInt(getTagValue("age", element)));            emp.setGender(getTagValue("gender", element));            emp.setRole(getTagValue("role", element));        }        return emp;    }    private static String getTagValue(String tag, Element element) {        NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();        Node node = (Node) nodeList.item(0);        return node.getNodeValue();    }}
  
 

The program output content is as follows:

Root element :EmployeesEmployee:: Name=Pankaj Age=29 Gender=Male Role=Java DeveloperEmployee:: Name=Lisa Age=35 Gender=Female Role=CSS Developer

In actual situations, we need to verify the validity of the XML file before parsing the XML file, and learn how to use XSD to verify the XML file.

The above is the Java & Xml tutorial (2). parse the content of the XML file using DOM. For more information, see PHP Chinese website (www.php1.cn )!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.