使用Java解析SOAP/XML出现问题

3

我编写了一个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>内。像这样:

<return>
 <id>123</id>
  <firstName>Jane</firstName>
  <lastName>Doe</lastName>
</return>
1个回答

3

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


谢谢,它有效。但是在信封中的url没有出现在输出中。

您需要按以下方式利用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/");

谢谢,它有效。但是在“信封”中的URL没有出现在输出中。 - Satheesh Natarajan
@SatheeshSanthosh - 它应该被写出来。这是一个链接,指向我准备的一个示例,您可以进行比较:http://blog.bdoughan.com/2012/08/handle-middle-of-xml-document-with-jaxb.html - bdoughan
我刚刚完全复制了你的代码,但它不起作用。 - Satheesh Natarajan
@SatheeshSanthosh - 试着添加writeNamespace方法:http://docs.oracle.com/javase/6/docs/api/javax/xml/stream/XMLStreamWriter.html#writeNamespace(java.lang.String,%20java.lang.String) - bdoughan
让我们在聊天中继续这个讨论 - Satheesh Natarajan
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接