阅读(558) (1)

FRAGMENT

2018-12-13 23:01:19 更新

Marshaller.JAXB_FRAGMENT

JAXB_FRAGMENT是一个多面手,在不同的输出场景下,表现出不同的效果。

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

在这里指定JAXB_FRAGMENT=true,表明结果不再声明XML头信息,得到的结果:



<one>
    <name>Test one</name>
</one>

可以看到,第一行的XML声明不见了。

如果使用到了SAX方式(见下一小节),可以发现如下不同:

    @Test
    public void test5_2() throws JAXBException {
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//      marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        marshaller.marshal(one, new MyContentHandler());
    }

输出结果:

startDocument
endDocument

如果将注释的一行代码放开,再次运行程序将不能得到任何输出。JAXB_FRAGMENT的默认值为false,在其他场景下也有不同的表现。