Java HTML / XML How to - Parse xml result received from client








Question

We would like to know how to parse xml result received from client.

Answer

import java.io.File;
import java.util.List;
/* w w  w.  j a va 2 s .  c o m*/
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

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

    Unmarshaller unmarshaller = jc.createUnmarshaller();
    File xml = new File("input.xml");
    WebResponse wr = (WebResponse) unmarshaller.unmarshal(xml);

    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(wr, System.out);
  }
  @XmlRootElement(name = "WebResponse")
  @XmlAccessorType(XmlAccessType.FIELD)
  public static class WebResponse {
    @XmlElement(name = "Response")
    private Response response = null;
  }
  @XmlAccessorType(XmlAccessType.FIELD)
  public static class Response {
    @XmlElementWrapper(name = "Info")
    @XmlElement(name = "Person")
    private List<Person> person;
    @XmlAttribute
    private String target;
  }
  @XmlAccessorType(XmlAccessType.FIELD)
  public static class Person {
    @XmlElement(name = "Id")
    private int id;
  }
}

input.xml/Output

<?xml version="1.0" encoding="UTF-8"?>
<WebResponse>//  ww  w . j  a v a  2  s. co m
    <Response target="test">
        <Info>
            <Person>
                <Id>1</Id>
            </Person>
            <Person>
                <Id>0</Id>
            </Person>
        </Info>
    </Response>
</WebResponse>