Can JAXB Incrementally Marshall An Object?

前端 未结 2 1150
星月不相逢
星月不相逢 2021-01-28 21:17

I\'ve got a fairly simple, but potentially large structure to serialize. Basically the structure of the XML will be:


   

        
2条回答
  •  暖寄归人
    2021-01-28 21:56

    How about the following?

    JAXBContext jaxbContext= JAXBContext.newInstance(MainObjectType.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
    
    OutputStreamWriter writer = new OutputStreamWriter(System.out);
    
    // Manually open the root element
    writer.write("");
    
    // Marshal the objects out individually
    marshaller.marshal(mainObjectType1, writer);
    marshaller.marshal(mainObjectType2, writer);
    marshaller.marshal(mainObjectType3, writer);
    marshaller.marshal(mainObjectType4, writer);
    ...
    
    // Manually close the root element
    writer.write("");
    writer.close();
    

    This assumes you have an @XmlRootElement on MainObjectType

    import javax.xml.bind.annotation.XmlRootElement;
    
    @XmlRootElement
    public class MainObjectType {
        ...
    }
    

提交回复
热议问题