Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

java - JAXB Fragmented Marshalling

I'm having some trouble successfully marshalling using the Marshaller.JAXB_FRAGMENT property. Here's a simple version of the XML i'm trying to output.

<Import>
    <WorkSets>
        <WorkSet>
            <Work>
            <Work>
            ...
            ..
            ...
        </WorkSet>
        <WorkSet>
            <Work>
            <Work>
            ...
        </WorkSet>
    <WorkSets>
<Import>

The <Import> and <WorkSets> elements are essentially just container elements that enclose a large number of <WorkSet> & <Work> elements. I'm currently trying to marshall at the <WorkSet>.

  1. Is it possible to initially marshal the <Import> and <WorkSets> elements and then from then on marshal at the <WorkSet> element and have the output be enclosed in the <Import><WorkSets> tags?
  2. When I'm marshaling at the WorkSet level it attaches the xmlns='http://namespace.com' attribute to the WorkSet tag, is there a way to marshal without the namespace attribute being attached to Workset?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Basically, it sounds like rather than constructing a full object tree with the container objects, you want to be able to stream a collection of WorkSet instances to marshal using JAXB.

The approach I would take is to use an XMLStreamWriter and marshal the WorkSet objects by wrapping them in a JAXBElement. I don't have tested sample code close at hand, so here's the rough code snippet that should put you on the write track:

FileOutputStream fos = new FileOutputStream("foo.xml");
XMLStreamWriter writer = XMLOutputFactory.newFactory().createXMLStreamWriter(fos);

writer.writeStartDocument();
writer.writeStartElement("Import");
writer.writeStartElement("WorkSets");

JAXBContext context = JAXBContext.newInstance(WorkSet.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); 
for (WorkSet instance : instances)
{
    JAXBElement<WorkSet> element = new JAXBElement<WorkSet>(QName.valueOf("WorkSet"), WorkSet.class, instance);
    m.marshal(element, writer);
}

writer.writeEndDocument(); // this will close any open tags
writer.close();

Note: The above is completely untested and may be messing something up in the wrapping part to write each instance of WorkSet. You need to wrap the WorkSet instances because they will not be annotated with @XmlRootElement and JAXB will otherwise refuse to marshal the objects.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...