Can JAXB Incrementally Marshall An Object?

前端 未结 2 1144
星月不相逢
星月不相逢 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:53

    You can marshal your object into a SAX or StAX stream.

    0 讨论(0)
  • 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("<simple_wrapper>");
    
    // 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("</simple_wrapper>");
    writer.close();
    

    This assumes you have an @XmlRootElement on MainObjectType

    import javax.xml.bind.annotation.XmlRootElement;
    
    @XmlRootElement
    public class MainObjectType {
        ...
    }
    
    0 讨论(0)
提交回复
热议问题