使用java解析SOAP / XML的问题

时间:2015-01-28 11:50:05

标签: java xml soap jaxb

我编写了一个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>

1 个答案:

答案 0 :(得分:3)

您只需要删除@XmlAttribute字段/属性上的id注释。


  

谢谢它有效。但是信封中的网址不是输出

您需要使用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/");