glebreutov
glebreutov

Reputation: 785

How to bind xml to bean

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?

Upvotes: 3

Views: 9406

Answers (4)

dogbane
dogbane

Reputation: 274532

In the past I have used XMLBeans for binding XML to Java types. It's really easy to use. You first have to compile your xml schema into Java types using the scomp command (or maven plugin etc) and use the types in your code.

There is an example of code in action here.

Upvotes: 1

bdoughan
bdoughan

Reputation: 148977

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>

Upvotes: 5

skel625
skel625

Reputation: 896

As an alternative to Castor and JAXB, Apache also has a project for doing XML to object binding:

Betwixt: http://commons.apache.org/betwixt/

Upvotes: 1

aar
aar

Reputation: 322

Try JAXB - http://jaxb.java.net/

An intro article for it http://www.javaworld.com/javaworld/jw-06-2006/jw-0626-jaxb.html

Upvotes: 4

Related Questions