How to bind xml to bean

glebreutov picture glebreutov · Sep 16, 2010 · Viewed 9k times · Source

In my application i use some API via HTTP and it returns responces as xml. I want automaticaly bind data from xml to beans.

For example bind following xml:

<xml>
   <userid>123456</userid>
   <uuid>123456</uuid>
</xml>

to this bean (maybe with help of annotations)

class APIResponce implement Serializable{

private Integer userid;
private Integer uuid;
....
}

What the simplest way to do this?

Answer

bdoughan picture bdoughan · Sep 16, 2010

I agree with using JAXB. As JAXB is a spec you can choose from multiple implementations:

Here is how you can do it with JAXB:

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="xml")
@XmlAccessorType(XmlAccessType.FIELD)
public class APIResponce {

    private Integer userid; 
    private Integer uuid; 

}

When used with the follow Demo class:

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(APIResponce.class);

        File xml = new File("input.xml");
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        APIResponce api = (APIResponce) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(api, System.out);
    }
}

Will produce the following XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xml>
    <userid>123456</userid>
    <uuid>123456</uuid>
</xml>