JAXB输出格式不正确。
问题:JAXB输出格式不正确的原因是什么?如何解决?
当使用StAX添加根元素时,在使用JAXB marshal到XMLStreamWriter时,需要设置JAXB_FRAGMENT属性。下面是一个示例代码:
import javax.xml.bind.*; import javax.xml.stream.*; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Zoo.class); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); XMLOutputFactory xof = XMLOutputFactory.newFactory(); XMLStreamWriter xsw = xof.createXMLStreamWriter(System.out); xsw.writeStartDocument(); xsw.writeStartElement("zoos"); Zoo zoo1 = new Zoo(); zoo1.linkId = 1; zoo1.name = "foo"; marshaller.marshal(zoo1, xsw); Zoo zoo2 = new Zoo(); zoo2.linkId = 2; zoo2.name = "bar"; marshaller.marshal(zoo2, xsw); xsw.writeEndElement(); xsw.writeEndDocument(); xsw.close(); } }
当marshal到XMLStreamWriter时,输出不会被格式化。
以下是示例输出:
1 foo 2 bar
要了解如何格式化StAX输出,请参考以下问题的答案:
- [StAX XML formatting in Java](https://stackoverflow.com/questions/290326)