Satheesh Natarajan
Satheesh Natarajan

Reputation: 459

Issue in parsing SOAP/XML using java

I had writing a java program to parser a SOAP/XML. This is my code.

public static void main(String[] args) throws Exception {
    Customer customer = new Customer();
    customer.id = 123;
    customer.firstName = "Jane";
    customer.lastName = "Doe";
    QName root = new QName("return");
    JAXBElement<Customer> je = new JAXBElement<Customer>(root, Customer.class, customer);

    XMLOutputFactory xof = XMLOutputFactory.newFactory();
    XMLStreamWriter xsw = xof.createXMLStreamWriter(System.out);
    xsw.writeStartDocument();
    xsw.writeStartElement("soapenv", "Envelope", "http://schemas.xmlsoap.org/soap/envelope/");
    xsw.writeStartElement("soapenv", "Body", "http://schemas.xmlsoap.org/soap/envelope/");
    xsw.writeStartElement("", "InitializePayment", "http://service.jaxws.blog/");
    xsw.writeStartElement("", "request", "http://service.jaxws.blog/");

    JAXBContext jc = JAXBContext.newInstance(Customer.class);
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
    marshaller.marshal(je, xsw);

    xsw.writeEndDocument();
    xsw.close();
}

I am getting output like this.

<?xml version="1.0" ?>
<soapenv:Envelope>
    <soapenv:Body>
    <InitializePayment>
     <request>
      <return id="123">
       <firstName>Jane</firstName>
       <lastName>Doe</lastName>
      </return>
     </request>
    </InitializePayment>
   </soapenv:Body>
</soapenv:Envelope>

But i need the output i which the id must be present as a tag inside a <return>. like this

<return>
 <id>123</id>
  <firstName>Jane</firstName>
  <lastName>Doe</lastName>
</return>

Upvotes: 3

Views: 381

Answers (1)

bdoughan
bdoughan

Reputation: 148977

You just need to remove the @XmlAttribute annotation on the id field/property.


thanks it works. But url which in a envelope is not come in output

You need to leverage the writeNamespace and writeDefaultNamespace methods as follows:

    xsw.writeStartElement("soapenv", "Envelope", "http://schemas.xmlsoap.org/soap/envelope/");
    xsw.writeNamespace("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
    xsw.writeStartElement("soapenv", "Body", "http://schemas.xmlsoap.org/soap/envelope/");
    xsw.writeStartElement("", "InitializePayment", "http://service.jaxws.blog/");
    xsw.writeDefaultNamespace("http://service.jaxws.blog/");
    xsw.writeStartElement("", "request", "http://service.jaxws.blog/");

Upvotes: 3

Related Questions