如何解析从客户端收到的xml结果

时间:2014-02-15 11:38:28

标签: java xml xml-parsing jaxb

以下代码向Web服务发送请求并接收结果。它成功发送请求并在控制台上显示结果,问题是我无法将xml解析为对象。

代码

    Request req = new Request();
    req.setLanguage(lang);

    webser webs = new webser();
    webs.setRequest(req);

        JAXBContext context = JAXBContext.newInstance(webser.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        URL url = new URL("http://example.com");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/xml");

        OutputStream os = connection.getOutputStream();
        m.marshal(webs, os);

        WebResponse result = (WebResponse) JAXB.unmarshal(connection.getInputStream(), WebResponse.class);
        System.err.println(">>>>>>" + result.getResponse().getInfogetPersons().get(0).getId()); 
                                                      //does not return anything

        //**** populating the object manually ****
        String edd = ">";
        person p1 = new Person();
        p1.setId(1);
        Person p2 = new Person();
        p2.setId(2);

        Info info = new linfo();
        info.getPersons().add(p1);
        info.gePersons().add(p2);

        Response r = new Response();
        r.setinfo(info);

        WebResponse result2 = new WebResponse();
        result2.setResponse(r);

        JAXB.marshal(result2, edd);
        System.err.println("Result:" + edd);   << does not return anything

        connection.disconnect();

    } catch (IOException e) {
        return e.getMessage(); 
    } catch (JAXBException e) {
        return e.getMessage();
    }

WebResponse.java

@XmlRootElement
public class WebResponse {

    @XmlElement(name = "Response")
    private Response response = null;

    public Response getResponse() {
        return response;
    }

    public void setResponse(Response response) {
        this.response = response;
    }  
}

Response.java

@XmlRootElement
public class Response {
   @XmlRootElement (name = "Info")
   private Info info;
   ...
}

Info.java

   @XmlRootElement
   public class Info {
      @XmlRootElement ( name = "Person")
      private List<Person> person;
      ....
   }

Person.java

   @XmlRootElement
   public class Person{

      private int Id;

      @XmlElement (name = "Id")
      public int getId() {
        return Id;
      }

      public void setId(int Id) {
        this.Id = Id;
      }
   }

来自服务器的实际响应

<?xml version="1.0" encoding="UTF-8"?>
<WebResponse>
      <Response target="test">
           <Info>
               <Person>
                   <Id>83094</Id>
                   <Age>34</Age>
                   <FGs>
                       <HF>0</HF>
                       <HI>1</HI>
                   </FGs>
                   <Rt>
                          <Rid parentid="412404">201735813</Rid>
                          <Rname>Special</Rname>
                          <Ca>2</Ca>
                          <link>www.google.com/test</link>
                  </Rt>
                  <Rt>
                          <Rid parentid="777777">787878</Rid>
                          <Rname>Standard</Rname>
                          <Ca>7</Ca>
                          <link>www.yahoo.com/blank</link>
                  </Rt>
             </Person>
             <Person>
               ....
              </Person>
              ......
         </Info>
         .....

1 个答案:

答案 0 :(得分:1)

您无法直接向List<Response>解组。您需要解组具有类型List<Response>的映射属性的类。

更新#1

您解组的类也需要与您解组的XML级别相对应。现在您的代码已经存在,您需要解组代表Web响应的类。如果要解组文档中的子部分,可以开始使用StAX解析XML,然后将XMLStreamReader推进到适当的位置并解组它。

更新#2

由于您有点挣扎,下面是您可以使用的模型。

Java模型

<强> WebResponse的

如果要注释该字段(实例变量),则应在类上指定@XmlAccessorType(XmlAccessType.FIELD)(参见:http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html)。

import javax.xml.bind.annotation.*;

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

    @XmlElement(name = "Response")
    private Response response = null;

}

<强>响应

您可以使用Info注释来表示分组元素,从而消除@XmlElementWrapper类(请参阅:http://blog.bdoughan.com/2010/09/jaxb-collection-properties.html)。

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
public class Response {

    @XmlElementWrapper(name = "Info")
    @XmlElement(name = "Person")
    private List<Person> person;

    @XmlAttribute
    private String target;

}

<强>人

您只需要使用您希望编组的顶级课程的@XmlRootElement

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
public class Person {

    @XmlElement(name = "Id")
    private int id;

}

演示代码

<强>演示

import java.io.File;
import javax.xml.bind.*;

public class Demo {

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

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

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

}

<强> input.xml中/输出

<?xml version="1.0" encoding="UTF-8"?>
<WebResponse>
    <Response target="test">
        <Info>
            <Person>
                <Id>83094</Id>
            </Person>
            <Person>
                <Id>0</Id>
            </Person>
        </Info>
    </Response>
</WebResponse>