1

我在按预期 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 来打印默认需要的标签。但是所有的写语句都打印在最后一个开始标签上,开始元素也是如此。

生成的输出是:

<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>

4

1 回答 1

2

对于您使用 StAX 添加根元素的用例,您还需要将 JAXB 编组到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();
    }

}

编组到XMLStreamWriter输出时不会格式化。

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

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

于 2013-03-30T10:01:13.573 回答