# JAXB `Unmarshaller`（解组器）示例

> 原文： [https://howtodoinjava.com/jaxb/jaxb-unmarshaller-example/](https://howtodoinjava.com/jaxb/jaxb-unmarshaller-example/)

JAXB [`Unmarshaller`](https://docs.oracle.com/javase/10/docs/api/javax/xml/bind/Unmarshaller.html)接口负责管理将 XML 数据反序列化为 Java 对象的过程。 可以将对象解组到各种输入源。

## 1.如何将 XML 解组到对象

#### 1.1 创建解组器

通常，要创建`Unmarshaller`，可以重用此代码。

```java
JAXBContext jaxbContext 	= JAXBContext.newInstance( Employee.class );
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

//Overloaded methods to unmarshal from different xml sources
Employee employee = (Employee) jaxbUnmarshaller.unmarshal( xmlSource );

```

#### 1.2 从`InputStream`解组

```java
InputStream inStream = new FileInputStream( "employee.xml" );

Employee employee = (Employee) jaxbUnmarshaller.unmarshal( inStream );

```

#### 1.3 从 URL 解组

```java
URL url = new URL( "http://localhost:8080/employee.xml" );

Employee employee = (Employee) jaxbUnmarshaller.unmarshal( url );

```

#### 1.4 解组字符串内容

```java
String xmlString = "...";

Employee employee = (Employee) jaxbUnmarshaller.unmarshal(new StringReader(xmlString));

```

#### 1.5 从`org.w3c.dom.Node`解组

```java
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(new File( "employee.xml")); //Node

Employee employee = (Employee) jaxbUnmarshaller.unmarshal( document );

```

## 2\. JAXB 解组器属性

当前，`Unmarshaller`上的所有 JAXB 供应器都不需要**所有属性**。 但是，某些供应器可能支持它们自己的一组供应器特定属性。

## 3.解组事件回调

您可以通过在 [JAXB 注释的](https://howtodoinjava.com/jaxb/jaxb-annotations/)类中添加这些回调方法**来自定义解组操作**，例如`Employee.java`。 您需要定义两个方法，这些方法将在`Unmarshaller`处理该类之前和之后监听。

*   `void beforeUnmarshal(Unmarshaller unmarshaller, Object parent) {}`
*   `void afterUnmarshal(Unmarshaller unmarshaller, Object parent) {}`

```java
package com.howtodoinjava.demo.model;

import java.io.Serializable;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "employee")
@XmlAccessorType(XmlAccessType.PROPERTY)
public class Employee implements Serializable {

	private static final long serialVersionUID = 1L;

	private Integer id;
	private String firstName;
	private String lastName;
	private Department department;

	public Employee() {
		super();
	}

	//Setters and Getters

	@Override
	public String toString() {
		return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", department="
				+ department + "]";
	}

	// It is called immediately after the object is created and before the unmarshalling begins.
	// The callback provides an opportunity to initialize JavaBean properties prior to unmarshalling.
	void beforeUnmarshal(Unmarshaller unmarshaller, Object parent) {
		System.out.println("Before Unmarshaller Callback");
	}

	// It is called after all the properties are unmarshalled for this object,
	// but before this object is set to the parent object.
	void afterUnmarshal(Unmarshaller unmarshaller, Object parent) {
		System.out.println("After Unmarshaller Callback");
	}
}

```

## 4\. JAXB 解组器示例

**将 XML 文件解组到 Java 对象**的示例。

```java
package com.howtodoinjava.demo;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import com.howtodoinjava.demo.model.Employee;

public class JaxbExample 
{
	public static void main(String[] args) 
	{
		String fileName = "employee.xml";

		jaxbXmlFileToObject(fileName);
	}

	private static void jaxbXmlFileToObject(String fileName) {

		File xmlFile = new File(fileName);

		JAXBContext jaxbContext;
		try 
		{
			jaxbContext = JAXBContext.newInstance(Employee.class);
			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

			Employee employee = (Employee) jaxbUnmarshaller.unmarshal(xmlFile);

			System.out.println(employee);
		}
		catch (JAXBException e) 
		{
			e.printStackTrace();
		}
	}
}

```

程序输出。

```java
Before Unmarshaller Callback
After Unmarshaller Callback

Employee [id=1, firstName=Lokesh, lastName=Gupta, department=Department [id=101, name=IT]]

```

其中`employee.xml`文件是：

```java
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
    <department>
        <id>101</id>
        <name>IT</name>
    </department>
    <firstName>Lokesh</firstName>
    <id>1</id>
    <lastName>Gupta</lastName>
</employee>

```

在有关使用 jaxb 在 Java 中解组**的注释部分中，向我提出您的问题。**

学习愉快！