How to bind xml with bean

In my application, I use some API via HTTP and it returns responses as xml. I want automatic data binding from xml to beans.

For example, bind the following xml:

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

to this bean (possibly with annotations)

class APIResponce implement Serializable{

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

What is the easiest way to do this?

+3
source share
4 answers

I agree to the use of JAXB. Since JAXB is a specification, you can choose from several implementations:

Here's 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 following 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);
    }
}

The following XML will be output:

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

Castor JAXB Apache XML :

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

+1

XMLBeans XML Java. . xml- Java, scomp ( maven ..) .

.

+1

Source: https://habr.com/ru/post/1765163/


All Articles