使用JAXB但没有获取值

时间:2017-08-01 05:26:24

标签: java jaxb

我正在尝试使用以下代码,但我没有得到这些值。

main
{
String example="<SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP:Body><ns0:findCustomerResponse xmlns:ns0=\"http://service.jaxws.blog/\"><return id=\"123\"><firstName>Jane</firstName><lastName>Doe</lastName></return></ns0:findCustomerResponse></SOAP:Body></SOAP:Envelope>";
ByteArrayInputStream bas=new ByteArrayInputStream(example.getBytes());
        JAXBContext jc = JAXBContext.newInstance(Customer.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        SOAPMessage message = MessageFactory.newInstance().createMessage(null,
                bas);
        JAXBElement<Customer> jb = unmarshaller.unmarshal(message.getSOAPBody(), Customer.class);

        Customer customer = jb.getValue();
        System.out.println(customer.id);
        System.out.println(customer.firstName);
        System.out.println(customer.lastName);
      }

@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {

    @XmlAttribute
    int id;

    String firstName;

    String lastName;

}

请说明为什么我没有获得价值

2 个答案:

答案 0 :(得分:1)

正如@Andreas所说,Customer嵌套在SOAP主体的两个深处,所以如果你想获得它,那么你可以使用以下内容,但我会说它不那么优雅:

JAXBElement<Customer> jb = unmarshaller.unmarshal(message.getSOAPBody().getFirstChild().getFirstChild(), Customer.class);

答案 1 :(得分:0)

做了一个小改动:

代替

JAXBElement jb = unmarshaller.unmarshal(message.getSOAPBody(),Customer.class);

JAXBElement jb = unmarshaller.unmarshal(message.getSOAPBody()。getFirstChild()。getFirstChild(),Customer.class);

我得到了答案

System.out.println(customer.id); // printed 123
System.out.println(customer.firstName); // printed Jane
System.out.println(customer.lastName); // printed Doe