java中xml解析器介绍

What is XML Parser?

xml 解析器提供了访问或修改用来表示数据的xml文件的能力。Java中提供了多种方式来解析xml文件。下面列出了Java中常用的xml解析器

  • Dom Parser - 将整个xml文件读入内存并构造一个含有继承关系的树结构
  • SAX Parser - 基于事件方式的解析器,不需要将整个文档读入内存。
  • JDOM Parser - 以类似于DOM解析器的方式解析文档,但更容使用。
  • StAX Parser - 以类似于SAX解析器的方式解析文档,但是以更有效的方式。
  • XPath Parser - 基于表达式解析XML,并与XSLT结合广泛使用。
  • DOM4J Parser - 一个使用 XPath 和 XSLT 和Java 集合框架解析XML文件的库,并提供了对DOM, SAX 和 JAXP 的支持。
  • Digester - xml和Java对象之间进行转换。
  • JAXB - xml和Java对象之间进行转换。
  • XStream - 一个在xml和Java对象之间进行转换的库

Digester Example

maven dependency

1
2
3
4
5
<dependency>
<groupId>commons-digester</groupId>
<artifactId>commons-digester</artifactId>
<version>1.8</version>
</dependency>

xml file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8"?>  
<root>
<student id="1" group="1">
<name>张三</name>
<sex>男</sex>
<age>18</age>
<birthday>1990-09-09</birthday>
</student>
<student id="2" group="2">
<name>李四</name>
<sex>女</sex>
<age>17</age>
<birthday>1990-10-10</birthday>
</student>
</root>

java object

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Root {
public ListstudentList = new ArrayList();

public void addStudent(Student student) {
this.studentList.add(student);
}
}
public class Student {
trueprivate Long id;
trueprivate String group;
trueprivate String name;
trueprivate String sex;
trueprivate Integer age;
trueprivate String birthday;

.... setter , getter
}

parse

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class XmlDigesterTester {
public static void main(String[] args) throws IOException, SAXException {
// XML文件的路径
String path = XmlDigesterTester.class.getClassLoader().getResource("com/xml/student.xml").getPath();
File input = new File(path);
Digester digester = new Digester();
// 初始化根对象Root(本案例的XML根目录命名为ROOT)
digester.addObjectCreate("root", "com.xml.Root");
// 将root节点上的属性全部注入到Root对象中。
digester.addSetProperties("root");
// 将所有匹配到的目录root/student转成javaBean对象Student(参见Student类)
digester.addObjectCreate("root/student", "com.xml.Student");
// 将节点root/student上的属性注入到Student对象中
digester.addSetProperties("root/student");
// 以下是root/student包含的节点根据名称映射,将节点值setter到对应的Student对象中。
digester.addBeanPropertySetter("root/student/name");
digester.addBeanPropertySetter("root/student/sex");
digester.addBeanPropertySetter("root/student/age");
digester.addBeanPropertySetter("root/student/birthday");
// 将所有匹配root/student节点,转化成了Student对象后,传入Root对象的addStudent方法中(参见Root类)
digester.addSetNext("root/student", "addStudent", "com.xml.Student");
// 定义好了上面的解析规则后,就可以开始进行解析工作了
Root root = (Root) digester.parse(input);
// 打印输入生成的对象结构
System.out.println(JSON.toJSONString(root));
}
}

XStream Example

对象类定义

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Person {
private String firstname;
private String lastname;
private PhoneNumber phone;
private PhoneNumber fax;
// ... constructors and methods
}

public class PhoneNumber {
private int code;
private String number;
// ... constructors and methods
}

初始化XStream

1
2
3
4
5
6
7
8
XStream xstream = new XStream();
//or
XStream xstream = new XStream(new DomDriver()); // does not require XPP3 library
//or
XStream xstream = new XStream(new StaxDriver()); // does not require XPP3 library starting with Java 6

xstream.alias("person", Person.class);
xstream.alias("phonenumber", PhoneNumber.class);

Serializing an object to XML

1
2
3
4
Person joe = new Person("Joe", "Walnes");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));
String xml = xstream.toXML(joe);

Deserializing an object back from XML

1
Person newJoe = (Person)xstream.fromXML(xml);

JAXB Example

对象类定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

trueString name;
trueint age;
trueint id;

truepublic String getName() {
truetruereturn name;
true}

true@XmlElement
truepublic void setName(String name) {
truetruethis.name = name;
true}

truepublic int getAge() {
truetruereturn age;
true}

true@XmlElement
truepublic void setAge(int age) {
truetruethis.age = age;
true}

truepublic int getId() {
truetruereturn id;
true}

true@XmlAttribute
truepublic void setId(int id) {
truetruethis.id = id;
true}
}

对象到xml文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBExample {
truepublic static void main(String[] args) {

true Customer customer = new Customer();
true customer.setId(100);
true customer.setName("mkyong");
true customer.setAge(29);

true try {

truetrueFile file = new File("C:\\file.xml");
truetrueJAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
truetrueMarshaller jaxbMarshaller = jaxbContext.createMarshaller();

truetrue// output pretty printed
truetruejaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

truetruejaxbMarshaller.marshal(customer, file);
truetruejaxbMarshaller.marshal(customer, System.out);

true } catch (JAXBException e) {
truetruee.printStackTrace();
true }

true}
}

xml到对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.mkyong.core;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class JAXBExample {
truepublic static void main(String[] args) {

true try {

truetrueFile file = new File("C:\\file.xml");
truetrueJAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);

truetrueUnmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
truetrueCustomer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
truetrueSystem.out.println(customer);

true } catch (JAXBException e) {
truetruee.printStackTrace();
true }

true}
}

参考

https://www.tutorialspoint.com/java_xml/java_xml_parsers.htm

http://www.everycoding.com/coding/78.html

https://www.mkyong.com/java/jaxb-hello-world-example/

http://www.mkyong.com/tutorials/java-xml-tutorials/

http://x-stream.github.io/

文章目录
  1. 1. What is XML Parser?
  2. 2. Digester Example
    1. 2.1. maven dependency
    2. 2.2. xml file
    3. 2.3. java object
    4. 2.4. parse
  3. 3. XStream Example
    1. 3.1. 对象类定义
    2. 3.2. 初始化XStream
    3. 3.3. Serializing an object to XML
    4. 3.4. Deserializing an object back from XML
  4. 4. JAXB Example
    1. 4.1. 对象类定义
    2. 4.2. 对象到xml文件
    3. 4.3. xml到对象
  5. 5. 参考
|