格式化输出

2018-12-23 22:29 更新

Marshaller.JAXB_FORMATTED_OUTPUT

默认的序列化操作,结果是正确的,但是显示成一行不便于阅读,可以通过添加属性JAXB_FORMATTED_OUTPUT来修正:

在此之前,为了能重用 JAXBContext,可以只初始化一个实例,对代码稍微重构一下:

    private static JAXBContext context;
    private static One one;

    
    @BeforeClass
    public static void init() throws JAXBException {
        // JAXBContext 是线程安全的 
        context = JAXBContext.newInstance(One.class);
        // 初始化全局的 Java bean
        one = new One();
        one.setName("Test one");
    }

这样可以更专注于核心逻辑,下面的代码使用JAXB_FORMATTED_OUTPUT来格式化输出:

    @Test
    public void test1() throws JAXBException {
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(one, System.out);
    }

得到的结果:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<one>
    <id>11</id>
    <name>Test one</name>
</one>

看起来舒服很多。

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号