我编写了一个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>
writeNamespace
方法:http://docs.oracle.com/javase/6/docs/api/javax/xml/stream/XMLStreamWriter.html#writeNamespace(java.lang.String,%20java.lang.String) - bdoughan