我在按预期 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>