Java & Xml tutorial (6) use JDOM to parse XML files

Source: Internet
Author: User
JDOM provides excellent javaxmlapis to facilitate reading, modifying, and generating XML documents. JDOM also provides packaging classes for users to select specific implementations from the interfaces of SAX, DOM, STAX event parsing, and STAX stream parsing.

JDOM provides excellent Java XML APIs to facilitate reading, modifying, and generating XML documents. JDOM also provides packaging classes for users to select specific implementations from the interfaces of SAX, DOM, STAX event parsing, and STAX stream parsing.

In this tutorial, we will learn how to use JDOM to read XML file information and convert it to a Java object.
JDOM is not part of the standard JDK. therefore, to use JDOM, you need to download the JDOM binary package from the official website, and then add the JDOM Jar package to the classpath of the project.
JDOM provides a packaging 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 useful methods to obtain the root element, child element list, and attribute values.
Important JDOM classes:
org.jdom2.input.DOMBuilder:Use the DOM parsing mechanism to parse XML and convert it to a JDOM Document object.
org.jdom2.input.SAXBuilder:Use the SAX parsing mechanism to parse XML and convert it to JDOM Document.
org.jdom2.input.StAXEventBuilderAndorg.jdom2.input.StAXStreamBuilderThe role is similar to the previous two.
org.jdom2.DocumentThe JDOM Document object provides a useful way to obtain the root element, read or modify the content of the element, and use it to obtain the root element of XML.
org.jdom2.DocumentProvides useful methods to obtain a set of sub-elements, obtain sub-element values, and obtain attribute values.
Next we start to use the case program to read the XML file and generate a Java object.
Employees. xml

 
     
  
           29        
   
    Pankaj
           
   
    Male
           
   
    Java Developer
       
      
  
           35        
   
    Lisa
           
   
    Female
           
   
    CEO
       
      
  
           40        
   
    Tom
           
   
    Male
           
   
    Manager
       
  
 

This xml file stores Employee information, which is represented by the Employee class.

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;    }}

Then, in the test program, use DOMBuilder to read the XML file and generate a set 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
 
   empListElements = root.getChildren("Employee");            List
  
    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);    }}
  
 

As you can see, here I use the DOM parsing packaging class to get the JDOM Document object.
Running 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

We can also use the SAX and STAX parsing mechanisms. we can do this using the following method:

/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);}

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

JDOM provides excellent Java XML APIs to facilitate reading, modifying, and generating XML documents. JDOM also provides packaging classes for users to select specific implementations from the interfaces of SAX, DOM, STAX event parsing, and STAX stream parsing.
In this tutorial, we will learn how to use JDOM to read XML file information and convert it to a Java object.
JDOM is not part of the standard JDK. therefore, to use JDOM, you need to download the JDOM binary package from the official website, and then add the JDOM Jar package to the classpath of the project.
JDOM provides a packaging 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 useful methods to obtain the root element, child element list, and attribute values.
Important JDOM classes:
org.jdom2.input.DOMBuilder:Use the DOM parsing mechanism to parse XML and convert it to a JDOM Document object.
org.jdom2.input.SAXBuilder:Use the SAX parsing mechanism to parse XML and convert it to JDOM Document.
org.jdom2.input.StAXEventBuilderAndorg.jdom2.input.StAXStreamBuilderThe role is similar to the previous two.
org.jdom2.DocumentThe JDOM Document object provides a useful way to obtain the root element, read or modify the content of the element, and use it to obtain the root element of XML.
org.jdom2.DocumentProvides useful methods to obtain a set of sub-elements, obtain sub-element values, and obtain attribute values.
Next we start to use the case program to read the XML file and generate a Java object.
Employees. xml

 
     
  
           29        
   
    Pankaj
           
   
    Male
           
   
    Java Developer
       
      
  
           35        
   
    Lisa
           
   
    Female
           
   
    CEO
       
      
  
           40        
   
    Tom
           
   
    Male
           
   
    Manager
       
  
 

This xml file stores Employee information, which is represented by the Employee class.

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;    }}

Then, in the test program, use DOMBuilder to read the XML file and generate a set 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
 
   empListElements = root.getChildren("Employee");            List
  
    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);    }}
  
 

As you can see, here I use the DOM parsing packaging class to get the JDOM Document object.
Running 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

We can also use the SAX and STAX parsing mechanisms. we can do this using the following method:

/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);}

Running the program will get the same output, because we only use different packaging classes, but the obtained JDOM Document object is 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 Java & Xml tutorial (6). use JDOM to parse the content of the XML file. 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.