Search code examples
javaxmljaxbsax

How to deserialize XML node to pojo in Java?


Say i have a very large XML file that contains thousands of nodes that contain all kinds of details, something like:

<Document>
    <Header>
    </Header>
    <Whatever>
        <Person>
            <Name>John Doe</Name>
            <Age>30</Age>
        </Person>
        <Person>
            <Name>Jane Doe</Name>
            <Age>30</Age>
        </Person>
        ...
    </Whatever>
</Document>

I want to stream the xml file, and each time it hits a Person node, it should give me a Person pojo. With StAX i can do that by creating the pojo manually, but i'm betting there are libraries out there that do that for me.


Solution

  • Define a class like:

    @XmlRootElement
    public class Person {
    
        @XmlElement(name = "Name")
        String name;
    
        @XmlElement(name = "Age")
        int age;
    }
    
    @XmlRootElement
    public class Header {    
    }
    
    @XmlRootElement
    public class Document {
    
        @XmlElement(name = "Header")
        Header header;
    
        @XmlElementWrapper(name = "Whatever")
        @XmlElement(name = "person")
        List<Person> people;
    }
    

    After use JAXB for unmarshalling xml to object.

    JAXBContext jaxbContext = JAXBContext.newInstance(Document.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    Document document = (Document) jaxbUnmarshaller.unmarshal(file);
    
    List<Person> people = document.getPeople();