Home > Backend Development > XML/RSS Tutorial > Java&Xml Tutorial (6) Using JDOM to parse XML files

Java&Xml Tutorial (6) Using JDOM to parse XML files

黄舟
Release: 2017-02-22 14:48:17
Original
1686 people have browsed it

JDOM provides a very excellent Java XML API to more conveniently read, modify, and generate XML documents. JDOM also provides wrapper classes for users to choose specific implementations from SAX, DOM, STAX event parsing, and STAX stream parsing.

In this tutorial, we learn to use JDOM to read XML file information and convert it into Java objects.
JDOM is not part of the standard JDK, so to use JDOM you need to download the JDOM binary package from the official website. After downloading, add the JDOM Jar package to the classpath of the project.
JDOM provides a wrapper class for us to choose the underlying XML parsing API. It provides four important classes that we can use to obtain the Document object of JDOM. The JDOM Document object provides very useful methods to get the root element, list of child elements, attribute values, etc.
Important classes of JDOM:
org.jdom2.input.DOMBuilder:Use the DOM parsing mechanism to parse XML and convert it into a JDOM Document object.
org.jdom2.input.SAXBuilder:Use the SAX parsing mechanism to parse XML and convert it to a JDOM Document.
org.jdom2.input.StAXEventBuilder and org.jdom2.input.StAXStreamBuilder have similar functions to the previous two and will not be described again.
org.jdom2.DocumentThe JDOM Document object provides useful methods to obtain the root element, read or modify the element content, etc. We will use it to obtain the root element of XML.
org.jdom2.Document Provides useful methods to obtain child element collections, obtain child element values, obtain attribute values ​​and other operations.
Next we start using the case program to read the XML file and generate Java objects.
employees.xml

<?xml version="1.0" encoding="UTF-8"?><Employees>
    <Employee id="1">
        <age>29</age>
        <name>Pankaj</name>
        <gender>Male</gender>
        <role>Java Developer</role>
    </Employee>
    <Employee id="2">
        <age>35</age>
        <name>Lisa</name>
        <gender>Female</gender>
        <role>CEO</role>
    </Employee>
    <Employee id="3">
        <age>40</age>
        <name>Tom</name>
        <gender>Male</gender>
        <role>Manager</role>
    </Employee></Employees>
Copy after login
Copy after login

This xml file stores employee information. We use the Employee class to represent employees.

package com.journaldev.xml;public class Employee {
    private int id;    
    private String name;    
    private String gender;    
    private int age;    
    private String role;    
    public int getId() {        
    return id;
    }    public void setId(int id) {        
    this.id = id;
    }    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:: ID="+this.id+" Name=" + this.name + " Age=" + this.age + " Gender=" + this.gender + 
                   " Role=" + this.role;
    }

}
Copy after login

Then use DOMBuilder in the test program to read the XML file and generate a collection of Employee objects.
JDOMXMLReader.java

package com.journaldev.xml.jdom;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
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 javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.DOMBuilder;
import org.jdom2.input.SAXBuilder;
import org.jdom2.input.StAXEventBuilder;
import org.jdom2.input.StAXStreamBuilder;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import com.journaldev.xml.Employee;
public class JDOMXMLReader {

    public static void main(String[] args) {
        final String fileName = "/Users/pankaj/employees.xml";
        org.jdom2.Document jdomDoc;
        try {
            //we can create JDOM Document from DOM, SAX and STAX Parser Builder classes
            jdomDoc = useDOMParser(fileName);
            Element root = jdomDoc.getRootElement();
            List<Element> empListElements = root.getChildren("Employee");
            List<Employee> empList = new ArrayList<>();
            for (Element empElement : empListElements) {
                Employee emp = new Employee();
                emp.setId(Integer.parseInt(empElement.getAttributeValue("id")));
                emp.setAge(Integer.parseInt(empElement.getChildText("age")));
                emp.setName(empElement.getChildText("name"));
                emp.setRole(empElement.getChildText("role"));
                emp.setGender(empElement.getChildText("gender"));
                empList.add(emp);
            }
            //lets print Employees list information
            for (Employee emp : empList)
                System.out.println(emp);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    //Get JDOM document from DOM Parser
    private static org.jdom2.Document useDOMParser(String fileName)
            throws ParserConfigurationException, SAXException, IOException {
        //creating DOM Document
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;
        dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(new File(fileName));
        DOMBuilder domBuilder = new DOMBuilder();
        return domBuilder.build(doc);

    }
}
Copy after login

As you can see, here I use the DOM parsing wrapper class to obtain the JDOM Document object.
Run the program output:

Employee:: ID=1 Name=Pankaj Age=29 Gender=Male Role=Java DeveloperEmployee:: ID=2 
Name=Lisa Age=35 Gender=Female Role=CEOEmployee:: ID=3 Name=Tom Age=40 Gender=Male Role=Manager
Copy after login

We can also use the SAX and STAX parsing mechanisms to complete. We can use the following method to complete:

/Get JDOM document from SAX Parserprivate static org.jdom2.Document useSAXParser(String fileName) throws JDOMException,
        IOException {
    SAXBuilder saxBuilder = new SAXBuilder();    
    return saxBuilder.build(new File(fileName));
}
//Get JDOM Document from STAX Stream Parser or STAX Event Parserprivate static org.jdom2.
Document useSTAXParser(String fileName, String type) throws FileNotFoundException, XMLStreamException, JDOMException{    
if(type.equalsIgnoreCase("stream")){
        StAXStreamBuilder staxBuilder = new StAXStreamBuilder();
        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(new FileInputStream(fileName));        
        return staxBuilder.build(xmlStreamReader);
    }
    StAXEventBuilder staxBuilder = new StAXEventBuilder();
    XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
    XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(new FileInputStream(fileName));    
    return staxBuilder.build(xmlEventReader);

}
Copy after login

Running the program will get the same output, because We just use different wrapper classes, but the JDOM Document objects obtained are the same.
The advantage of using JDOM is that we can easily switch the underlying parsing mechanism without changing the processing code.

JDOM provides a very excellent Java XML API to more conveniently read, modify, and generate XML documents. JDOM also provides wrapper classes for users to choose specific implementations from SAX, DOM, STAX event parsing, and STAX stream parsing.
In this tutorial, we learn to use JDOM to read XML file information and convert it into Java objects.
JDOM is not part of the standard JDK, so to use JDOM you need to download the JDOM binary package from the official website. After downloading, add the JDOM Jar package to the classpath of the project.
JDOM provides a wrapper class for us to choose the underlying XML parsing API. It provides four important classes that we can use to obtain the Document object of JDOM. The JDOM Document object provides very useful methods to get the root element, list of child elements, attribute values, etc.
Important classes of JDOM:
org.jdom2.input.DOMBuilder:Use the DOM parsing mechanism to parse XML and convert it into a JDOM Document object.
org.jdom2.input.SAXBuilder:Use the SAX parsing mechanism to parse XML and convert it to a JDOM Document.
org.jdom2.input.StAXEventBuilder and org.jdom2.input.StAXStreamBuilder have similar functions to the previous two and will not be described again.
org.jdom2.DocumentThe JDOM Document object provides useful methods to obtain the root element, read or modify the element content, etc. We will use it to obtain the root element of XML.
org.jdom2.Document Provides useful methods to obtain child element collections, obtain child element values, obtain attribute values ​​and other operations.
Next we start using the case program to read the XML file and generate Java objects.
employees.xml

<?xml version="1.0" encoding="UTF-8"?><Employees>
    <Employee id="1">
        <age>29</age>
        <name>Pankaj</name>
        <gender>Male</gender>
        <role>Java Developer</role>
    </Employee>
    <Employee id="2">
        <age>35</age>
        <name>Lisa</name>
        <gender>Female</gender>
        <role>CEO</role>
    </Employee>
    <Employee id="3">
        <age>40</age>
        <name>Tom</name>
        <gender>Male</gender>
        <role>Manager</role>
    </Employee></Employees>
Copy after login
Copy after login

This xml file stores employee information. We use the Employee class to represent employees.

package com.journaldev.xml;
public class Employee {
    private int id;    
    private String name;    
    private String gender;    
    private int age;    
    private String role;    
    public int getId() {        
    return id;
    }    public void setId(int id) {        
    this.id = id;
    }    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:: ID="+this.id+" Name=" + this.name + " Age=" + this.age + " Gender=" + this.gender + 
                   " Role=" + this.role;
    }

}
Copy after login

Then use DOMBuilder in the test program to read the XML file and generate a collection of Employee objects.
JDOMXMLReader.java

package com.journaldev.xml.jdom;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
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 javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.jdom2.Element;import org.jdom2.JDOMException;
import org.jdom2.input.DOMBuilder;
import org.jdom2.input.SAXBuilder;
import org.jdom2.input.StAXEventBuilder;
import org.jdom2.input.StAXStreamBuilder;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import com.journaldev.xml.Employee;
public class JDOMXMLReader {

    public static void main(String[] args) {
        final String fileName = "/Users/pankaj/employees.xml";
        org.jdom2.Document jdomDoc;
        try {
            //we can create JDOM Document from DOM, SAX and STAX Parser Builder classes
            jdomDoc = useDOMParser(fileName);
            Element root = jdomDoc.getRootElement();
            List<Element> empListElements = root.getChildren("Employee");
            List<Employee> empList = new ArrayList<>();
            for (Element empElement : empListElements) {
                Employee emp = new Employee();
                emp.setId(Integer.parseInt(empElement.getAttributeValue("id")));
                emp.setAge(Integer.parseInt(empElement.getChildText("age")));
                emp.setName(empElement.getChildText("name"));
                emp.setRole(empElement.getChildText("role"));
                emp.setGender(empElement.getChildText("gender"));
                empList.add(emp);
            }
            //lets print Employees list information
            for (Employee emp : empList)
                System.out.println(emp);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    //Get JDOM document from DOM Parser
    private static org.jdom2.Document useDOMParser(String fileName)
            throws ParserConfigurationException, SAXException, IOException {
        //creating DOM Document
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;
        dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(new File(fileName));
        DOMBuilder domBuilder = new DOMBuilder();
        return domBuilder.build(doc);

    }
}
Copy after login

As you can see, here I use the DOM parsing wrapper class to obtain the JDOM Document object.
Output of running the program:

Employee:: ID=1 Name=Pankaj Age=29 Gender=Male Role=Java DeveloperEmployee:: 
ID=2 Name=Lisa Age=35 Gender=Female Role=CEOEmployee:: ID=3 Name=Tom Age=40 Gender=Male Role=Manager
Copy after login

We can also use the SAX and STAX parsing mechanisms to complete. We can use the following method to complete:

/Get JDOM document from SAX Parserprivate static org.jdom2.Document useSAXParser(String fileName) throws JDOMException,
        IOException {
    SAXBuilder saxBuilder = new SAXBuilder();    return saxBuilder.build(new File(fileName));
}
//Get JDOM Document from STAX Stream Parser or STAX Event Parserprivate static org.jdom2.Document 
useSTAXParser(String fileName, String type) throws FileNotFoundException, XMLStreamException, JDOMException{    
if(type.equalsIgnoreCase("stream")){
        StAXStreamBuilder staxBuilder = new StAXStreamBuilder();
        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(new FileInputStream(fileName));        
        return staxBuilder.build(xmlStreamReader);
    }
    StAXEventBuilder staxBuilder = new StAXEventBuilder();
    XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
    XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(new FileInputStream(fileName));    
    return staxBuilder.build(xmlEventReader);

}
Copy after login

Running the program will get the same output, because We just use different wrapper classes, but the JDOM Document objects obtained are the same.
The advantage of using JDOM is that we can easily switch the underlying parsing mechanism without changing the processing code.

The above is the content of Java&Xml tutorial (6) using JDOM to parse XML files. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template