使用 java 解析 SOAP/XML 时出现问题

Issue in parsing SOAP/XML using java

我编写了一个 java 程序来解析 SOAP/XML。这是我的代码。

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();
}

我得到这样的输出。

<?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>

但我需要 id 必须作为标签出现在 <return> 中的输出 i。像这样

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

您只需删除 id field/property 上的 @XmlAttribute 注释。


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

您需要利用 writeNamespacewriteDefaultNamespace 方法,如下所示:

    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/");