jdom 读取xml_JDOM分析器–将XML文件读取为Java对象

jdom 读取xml

JDOM parser provides us a great Java XML API to read, edit and write XML documents easily. JDOM provides wrapper classes to chose your underlying implementation from SAX Parser, DOM Parser, STAX Event Parser and STAX Stream Parser.

JDOM解析器为我们提供了一个出色的Java XML API,可轻松读取,编辑和写入XML文档。 JDOM提供了包装器类,可以从SAX ParserDOM ParserSTAX Event ParserSTAX Stream Parser中选择基础实现。

JDOM解析器 (JDOM Parser)

In this tutorial, we will learn how to read XML file to Object using JDOM Parser.

在本教程中,我们将学习如何使用JDOM Parser将XML文件读取到Object。

JDOM is not part of standard JDK, so to work with JDOM you will need to download it’s binaries from JDOM Official Website. Once binaries are downloaded, include JDOM jar in your project classpath and you are good to start using it. For this tutorial, I am using current JDOM version 2.0.4 (jdom-2.0.4.jar).

JDOM不是标准JDK的一部分,因此要使用JDOM,您需要从JDOM官方网站下载其二进制文件。 下载二进制文件后,将JDOM jar包含在项目类路径中,您可以开始使用它了。 对于本教程,我正在使用当前的JDOM版本2.0.4( jdom-2.0.4.jar )。

As I said earlier, JDOM provides wrapper classes to chose your preferred XML API, it comes with four important classes using which we can get JDOM Document Object. JDOM Document object provides useful methods to get the root element, list of child elements, getting attribute value for an element and getting element value from name.

如前所述,JDOM提供了包装器类来选择您首选的XML API,它带有四个重要的类,通过这些类我们可以获取JDOM Document Object。 JDOM Document对象提供了有用的方法来获取根元素,子元素列表,获取元素的属性值以及从名称获取元素值。

JDOM解析器重要类 (JDOM Parser Important Classes)

  1. org.jdom2.input.DOMBuilder: Uses DOM Parser to parse the XML and transform it to JDOM Document.

    org.jdom2.input.DOMBuilder :使用DOM解析器解析XML并将其转换为JDOM Document。
  2. org.jdom2.input.SAXBuilder: Uses SAX Parser to parse the XML and transform it to JDOM Document.

    org.jdom2.input.SAXBuilder :使用SAX Parser解析XML并将其转换为JDOM Document。
  3. org.jdom2.input.StAXEventBuilder: Uses STAX Event Parser to parse the XML and transform it to JDOM Document.

    org.jdom2.input.StAXEventBuilder :使用STAX事件解析器解析XML并将其转换为JDOM Document。
  4. org.jdom2.input.StAXStreamBuilder: Uses STAX Stream Parser to parse the XML and transform it to JDOM Document.

    org.jdom2.input.StAXStreamBuilder :使用STAX流解析器来解析XML并将其转换为JDOM Document。
  5. org.jdom2.Document: JDOM Document provides useful methods to get root element, read, edit and write content to Elements. Here we will use it to get the root element from XML.

    org.jdom2.Document :JDOM Document提供了有用的方法来获取根元素,读取,编辑内容以及将内容写入Elements。 在这里,我们将使用它从XML获取根元素。
  6. org.jdom2.Element: Provides useful methods to get list of child elements, get child element value, get attribute values.

    org.jdom2.Element :提供有用的方法来获取子元素列表,获取子元素值,获取属性值。

JDOM示例 (JDOM Example)

Let’s start with our sample program to read XML to Object using JDOM Parser.

让我们从示例程序开始,使用JDOM Parser读取XML到Object。

employees.xml

employees.xml



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

Employee object to represent the Employee element in the XML.

Employee对象,表示XML中的Employee元素。

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

Here is the test program using DOMBuilder to read the XML file to list of Employee object.

这是使用DOMBuilder读取XML文件到Employee对象列表的测试程序。

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 that I am using DOM parser wrapper class to get the JDOM Document object.

如您所见,我正在使用DOM解析器包装器类来获取JDOM Document对象。

When I run above program, here is the output.

当我运行上面的程序时,这是输出。

Employee:: ID=1 Name=Pankaj Age=29 Gender=Male Role=Java Developer
Employee:: ID=2 Name=Lisa Age=35 Gender=Female Role=CEO
Employee:: ID=3 Name=Tom Age=40 Gender=Male Role=Manager

We can use SAX and STAX Parser also, here are other useful methods that we can use to use them.

我们也可以使用SAXSTAX Parser ,这是我们可以用来使用它们的其他有用方法。

//Get JDOM document from SAX Parser
    private 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 Parser
    private 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);
        
    }

You will get the same output with above methods also because they are just changing the parser and finally returning the same Document.

使用上述方法,您将获得相同的输出,因为它们只是更改解析器并最终返回相同的Document。

Benefit of using JDOM is that you can switch from SAX to DOM to STAX Parser easily, you can provide factory methods to let client application chose the implementation.

使用JDOM的好处是,您可以轻松地从SAX切换到DOM,再切换到STAX Parser,可以提供工厂方法来让客户端应用程序选择实现。

You might want to head over to any of these.

您可能想要前往其中任何一个。

  • DOM Parser Read XML Example

    DOM解析器读取XML示例
  • STAX Parser Read XML Example

    STAX分析器读取XML示例
  • SAX Parser Read XML Example

    SAX Parser读取XML示例

翻译自: https://www.journaldev.com/1206/jdom-parser-read-xml-file-object-java

jdom 读取xml

你可能感兴趣的:(列表,java,xml,python,hadoop)