JAXB_FORMATTED_OUTPUT
时间: 2024-04-23 17:20:39 浏览: 138
JAXB_FORMATTED_OUTPUT是Java Architecture for XML Binding(JAXB)库中的一个属性,用于控制生成的XML输出是否进行格式化。当设置JAXB_FORMATTED_OUTPUT为true时,生成的XML将会进行缩进和换行,使其更易读。当设置为false时,生成的XML将不进行格式化,以节省空间。
以下是一个示例,演示如何使用JAXB_FORMATTED_OUTPUT属性来控制XML输出的格式化:
```java
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;
public class JAXBExample {
public static void main(String[] args) {
try {
// 创建JAXBContext对象
JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
// 创建Marshaller对象
Marshaller marshaller = jaxbContext.createMarshaller();
// 设置JAXB_FORMATTED_OUTPUT属性
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// 创建Employee对象
Employee employee = new Employee();
employee.setId(1);
employee.setName("John Doe");
employee.setAge(30);
// 将Employee对象转换为XML字符串
StringWriter stringWriter = new StringWriter();
marshaller.marshal(employee, stringWriter);
String xmlString = stringWriter.toString();
// 输出XML字符串
System.out.println(xmlString);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
```
运行上述代码,将会输出格式化后的XML字符串,如下所示:
```xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
<id>1</id>
<name>John Doe</name>
<age>30</age>
</employee>
```
阅读全文