Search code examples
javaxmlxml-parsingjsoupdom4j

How can I create Generics for XML Parsing?


I currently using jsoup and sometimes dom4j for parsing string of xml. Here's an example on how I do it using jsoup.

Document doc = Jsoup.parse(xml);
Elements root = doc.select("person");
for(Elements elem : elements){
Person person = new Person();
person.setFirstname(elem.select("firstName").text());
person.setLastname(elem.select("lastName").text());
person.setAddress(elem.select("address").text());
//other setters here
}

Everytime I have to parse xml I have to get all elements and set to setters of POJO. Now I want to create a Generics where I only have to do is to passed a string of xml and a class of POJO then it will set all the values of fields based on all the elements of xml. How can I do it? Any ideas?

Thanks in advance.


Solution

  • JAXB is the way to go.

    Note: It is included in JAVA 1.6 and later versions

    Add XML tags to your POJO (XmlRootElement is enough for simple objects, XmlElement can also be added to variables)

    import javax.xml.bind.annotation.XmlRootElement;
    
    @XmlRootElement(name = "Person")
    public class Person {
    
        private String firstName;
    
        private String lastName;
    
        private String address;
    
        public final String getFirstName() {
            return firstName;
        }
    
        public final void setFirstName(String firstName) {
            this.firstName = firstName;
        }
    
        public final String getLastName() {
            return lastName;
        }
    
        public final void setLastName(String lastName) {
            this.lastName = lastName;
        }
    
        public final String getAddress() {
            return address;
        }
    
        public final void setAddress(String address) {
            this.address = address;
        }
    
        @Override
        public String toString() {
            return "FirstName: " + firstName + " LastName: " + lastName + " Address: " + address;
        }
    
    }
    

    Use Unmarshaller to create the POJO from the xml file.

        File file = new File("<Path to Xml file>");
        JAXBContext context = JAXBContext.newInstance(Person.class);
        Unmarshaller unmarsheller = context.createUnmarshaller();
        Person person = (Person) unmarsheller.unmarshal(file);
        System.out.println(person);
    

    You can use Marshaller to create the XML from the POJO also.

    There are more examples available here to create complex objects, add lists, arrays.

    Note: It is not available in Android Platform, If you want to use it on android you can use SimpleXML with almost same implementation