user3428736
user3428736

Reputation: 914

Using JAXB but not getting the values

I am trying to use the below code but I am not getting the values.

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;

}

Please suggest why I am not getting values

Upvotes: 0

Views: 93

Answers (2)

deepakl
deepakl

Reputation: 172

Just made a small change :

Replaced

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

with

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

And I got the answer

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

Upvotes: 0

mgyongyosi
mgyongyosi

Reputation: 2677

As @Andreas said, the Customer is nested two deep in the SOAP body, so if you would like to get it then you can use the following, but I would say it's not so elegant:

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

Upvotes: 1

Related Questions