32.md 5.3 KB
Newer Older
W
wizardforcel 已提交
1
# JAXB `Marshaller`(编组器)示例
W
wizardforcel 已提交
2 3 4

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

W
wizardforcel 已提交
5
JAXB [`Marshaller`](https://docs.oracle.com/javase/10/docs/api/javax/xml/bind/Marshaller.html)接口负责管理将 Java 内容树即 **Java 对象转换为 XML** 数据的过程。 可以将 XML 编组到各种输出目标。
W
wizardforcel 已提交
6 7 8

## 1\. JAXB 编组对象到 XML

W
wizardforcel 已提交
9
#### 1.1 创建编组器
W
wizardforcel 已提交
10 11 12 13 14 15 16 17 18 19 20 21 22 23

通常,要创建编组器,可以重用此代码。

```java
JAXBContext jaxbContext 	= JAXBContext.newInstance( Employee.class );
Marshaller jaxbMarshaller 	= jaxbContext.createMarshaller();

Employee employeeObj = new Employee(1, "Lokesh", "Gupta", new Department(101, "IT"));

//Overloaded methods to marshal to different outputs
jaxbMarshaller.marshal(employeeObj);

```

W
wizardforcel 已提交
24
#### 1.2 编组 XML 文件
W
wizardforcel 已提交
25 26 27 28 29 30 31

```java
OutputStream os = new FileOutputStream( "employee.xml" );
jaxbMarshaller.marshal( employeeObj, os );

```

W
wizardforcel 已提交
32
#### 1.3 编组至 SAX `ContentHandler`
W
wizardforcel 已提交
33 34 35 36 37 38 39 40

假设`MyContentHandler`[`org.xml.sax.ContentHandler`](https://docs.oracle.com/javase/7/docs/api/org/xml/sax/ContentHandler.html) 的实例。

```java
jaxbMarshaller.marshal( employeeObj, new MyContentHandler() );

```

W
wizardforcel 已提交
41
#### 1.4 编组 DOM 文件
W
wizardforcel 已提交
42 43 44 45 46 47 48 49 50 51 52

```java
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();

jaxbMarshaller.marshal( employeeObj, doc );

```

W
wizardforcel 已提交
53
#### 1.5 编组并打印到控制台
W
wizardforcel 已提交
54 55 56 57 58 59

```java
m.marshal( employeeObj, new PrintWriter( System.out ) );

```

W
wizardforcel 已提交
60
## 2\. JAXB `Marshaller`属性
W
wizardforcel 已提交
61 62 63 64 65 66 67 68

```java
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
//or
jaxbMarshaller.setProperty("jaxb.formatted.output", Boolean.TRUE);

```

W
wizardforcel 已提交
69
所有 JAXB 供应器都必须支持以下属性集。 一些供应器可能支持其他属性。
W
wizardforcel 已提交
70

W
wizardforcel 已提交
71
*   **`jaxb.encoding`** - 编组 XML 数据时使用的输出编码。 如果未指定此属性,则默认情况下`Marshaller`将使用“`UTF-8`”。
W
wizardforcel 已提交
72 73 74 75
*   **`jaxb.formatted.output`** - 值可以是`true``false``Marshaller`是否将使用换行符和缩进来格式化所得的 XML 数据。 默认值为`false`
*   **`jaxb.schemaLocation`** – 允许客户端应用在生成的 XML 数据中指定`xsi:schemaLocation`属性。
*   **`jaxb.noNamespaceSchemaLocation`** – 它允许客户端应用在生成的 XML 数据中指定`xsi:noNamespaceSchemaLocation`属性。
*   **`jaxb.fragment`** – 它确定`Marshaller`是否将生成文档级事件。 值可以是`true``false`
W
wizardforcel 已提交
76

W
wizardforcel 已提交
77
## 3.`Marshaller`回调方法
W
wizardforcel 已提交
78

W
wizardforcel 已提交
79
您可以通过 JAXB 注释类中的**自定义编组操作**,例如 `Employee.java`。 您需要定义两个方法,这些方法将在编组程序处理该类之前和之后进行监听。 在这些方法中,您可以执行诸如设置额外字段之类的操作。
W
wizardforcel 已提交
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192

```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 + "]";
	}

	// Invoked by Marshaller after it has created an instance of this object.
	boolean beforeMarshal(Marshaller marshaller) {
		System.out.println("Before Marshaller Callback");
		return true;
	}

	// Invoked by Marshaller after it has marshalled all properties of this object.
	void afterMarshal(Marshaller marshaller) {
		System.out.println("After Marshaller Callback");
	}
}

```

## 4\. JAXB 编组示例

**将 Java 对象编组为 XML 字符串**的示例。

```java
package com.howtodoinjava.demo;

import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import com.howtodoinjava.demo.model.Department;
import com.howtodoinjava.demo.model.Employee;

public class JaxbExample 
{
	public static void main(String[] args) 
	{
		Employee employee = new Employee(1, "Lokesh", "Gupta", new Department(101, "IT"));

		jaxbObjectToXML(employee);
	}

	private static void jaxbObjectToXML(Employee employee) 
	{
	    try {
	        JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
	        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

	        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // To format XML

	        //Print XML String to Console
	        jaxbMarshaller.marshal(employee, System.out);

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

```

程序输出。

```java
Before Marshaller Callback
After Marshaller Callback

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

```

将我的问题放在评论部分。

学习愉快!