Can a part of XML be marshalled using JAXB (or JAXB + StAX)?

≡放荡痞女 提交于 2019-12-05 14:40:16
bdoughan

You could do the following with JAXB and StAX:

import javax.xml.bind.*;
import javax.xml.stream.*;
import javax.xml.stream.events.XMLEvent;
import java.io.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        XMLInputFactory xif = XMLInputFactory.newFactory();
        XMLOutputFactory xof = XMLOutputFactory.newFactory();

        try(
           FileInputStream in = new FileInputStream("in.xml");
           FileOutputStream out = new FileOutputStream("out.xml");
        ) {
            XMLEventReader xer = xif.createXMLEventReader(in);
            XMLEventWriter xew = xof.createXMLEventWriter(out);

            JAXBContext jc = JAXBContext.newInstance(File.class);
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);

            while(xer.hasNext()) {
                if(xer.peek().isStartElement() && xer.peek().asStartElement().getName().getLocalPart().equals("file")) {
                    // Unmarshal the File object from the XMLEventReader
                    File file = (File) unmarshaller.unmarshal(xer);

                    // Modify the File object
                    file.description = "NEW DESCRIPTION";

                    // Marshal the File object to the XMLEventWriter
                    marshaller.marshal(file, xew);
                } else {
                    // Copy node from reader to writer
                    xew.add(xer.nextEvent());
                }
            }
        }
    }

}

Try the Binder, see the tutorial.

If you want StAX, see the methods:

  • javax.xml.bind.Unmarshaller.unmarshal(XMLStreamReader, Class<T>)
  • javax.xml.bind.Marshaller.marshal(Object, XMLStreamWriter)

You can unmarshal a known klass from stream, process it and marshal back. This can even be done in a "filter"-like process. I.e.:

  • You parse your XML via StAX.
  • You check the coming events until you see someting you want to process.
  • Irrelevant events are passed further on.
  • When you get a relevant event, you unmarshal your class with JAXB, process the pojo and marshal it back to the stream writer.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!