Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have an XML structure which is very huge. I want to update the parts of this XML, by unmarshalling one element and then applying business logic.

I am able to unmarshal a child element into a POJO. I want to make changes to this POJO in Java and then update it back to the XML at the same location.

Is this possible in JAXB? Or by using the combination of JAXB + StAX.

Example Structure :

 <folder id="c5718b36-bab1-4c08-8f75-8e2f9aee42c5" name="Folder-1">
        <description> folder Desc</description>
        <createdBy>User2</createdBy>
        <hidden>false</hidden>

        <file id="4f2efb42-0604-4878-9e1e-ae90d66fb836" name="File-1">
            <description>file desc</description>
            <createdBy>User1</createdBy>
            <hidden>false</hidden>
        </file>
 </folder>

In the above example, I am able to unmarshal a 'file' element into a POJO. I want to make changes to this POJO and then update the same in the XML file at its correct location.

How can I accomplish this ?

Please help me. Thanks.

like image 522
metal7 Avatar asked Sep 03 '14 11:09

metal7


Video Answer


1 Answers

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());
                }
            }
        }
    }

}
like image 114
bdoughan Avatar answered Sep 20 '22 00:09

bdoughan