JAXB输出格式不正确

时间:2013-03-30 07:41:05

标签: jsf-2 jaxb marshalling maven-jaxb2-plugin

我将代码编组为预期的XML

有问题
public void xmleg() throws XMLStreamException
    {


     XMLOutputFactory factory = XMLOutputFactory.newInstance();
     XMLStreamWriter writer = factory.createXMLStreamWriter(System.out);
     writer.writeStartDocument();
     writer.writeStartElement("Zoos1"); 


         QName q=new QName("","Zoo"); 
         for(Zoo add: zoo_list)
        {
        try 
         {

          JAXBContext jaxbContext = JAXBContext.newInstance(Zoos.class);
              Marshaller jaxbMarshaller = jaxbContext.createMarshaller();



             jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
             jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
             jaxbMarshaller.marshal(new JAXBElement<Zoot>(q,Zoo.class,add),System.out);

         } catch (JAXBException e) {
            e.printStackTrace();
              }
        }
        writer.writeEndDocument();
         writer.close();
        }


}

使用XMLStreamWriter打印默认所需的标签。但是所有的write语句都打印在最后的Start标签,start元素上。

生成的输出为:

<Zoo>
    <linkId>0</linkId>
    <name>fjjfjfrj</name>

</Zoo>

<Zoo>
    <linkId>0</linkId>
    <name>fgjfjfj</name>
</Zoo>
<?xml version="1.0" ?><Zoos></Zoos>

预期输出应为:

<?xml version="1.0" ?>

<Zoo>
    <linkId>0</linkId>
    <name>fjjfjfrj</name>
    </Zoo>

 <Zoo>
    <linkId>0</linkId>
    <name>fgjfjfj</name>
</Zoo>

1 个答案:

答案 0 :(得分:1)

对于使用StAX添加根元素的用例,您还需要具有XMLStreamWriter的JAXB编组。当编组到文档中间时,您需要确保设置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();
    }

}

当编组到XMLStreamWriter时,输出将不会被格式化。

<?xml version="1.0" ?><zoos><zoo><linkId>1</linkId><name>foo</name></zoo><zoo><linkId>2</linkId><name>bar</name></zoo></zoos>

有关格式化StAX输出的帮助,请查看以下问题的答案: