Reputation: 1891
I have a problem while decoding SOAP Envelope. Here is my XML
<?xml version="1.0"?>
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:tns="http://c.com/partner/">
<env:Header>c
<tns:MessageId env:mustUnderstand="true">3</tns:MessageId>
</env:Header>
<env:Body>
<GetForkliftPositionResponse xmlns="http://www.c.com">
<ForkliftId>PC006</ForkliftId>
</GetForkliftPositionResponse>
</env:Body>
</env:Envelope>
I use the following code to decode the body, but it always return to the namespace tns:MessageID, not to the env:body. I also would like to convert the XMLStreamReader to string for debugging issues, is it possible?
XMLInputFactory xif = XMLInputFactory.newFactory();
xif.setProperty("javax.xml.stream.isCoalescing", true); // decode entities into one string
StringReader reader = new StringReader(Message);
String SoapBody = "";
XMLStreamReader xsr = xif.createXMLStreamReader( reader );
xsr.nextTag(); // Advance to header tag
xsr.nextTag(); // advance to envelope
xsr.nextTag(); // advance to body
Upvotes: 2
Views: 2979
Reputation: 122364
Initially the xsr is pointing to before the document event (i.e. the XML declaration), and nextTag()
advances to the next tag, not the next sibling element:
xsr.nextTag(); // Advance to opening envelope tag
xsr.nextTag(); // advance to opening header tag
xsr.nextTag(); // advance to opening MessageId
If you want to skip to the body a better idiom would be
boolean foundBody = false;
while(!foundBody && xsr.hasNext()) {
if(xsr.next() == XMLStreamConstants.START_ELEMENT &&
"http://www.w3.org/2003/05/soap-envelope".equals(xsr.getNamespaceURI()) &&
"Body".equals(xsr.getLocalName())) {
foundBody = true;
}
}
// if foundBody == true, then xsr is now pointing to the opening Body tag.
// if foundBody == false, then we ran out of document before finding a Body
if(foundBody) {
// advance to the next tag - this will either be the opening tag of the
// element inside the body, if there is one, or the closing Body tag if
// there isn't
if(xsr.nextTag() == XMLStreamConstants.START_ELEMENT) {
// now pointing at the opening tag of GetForkliftPositionResponse
} else {
// now pointing at </env:Body> - body was empty
}
}
Upvotes: 1
Reputation: 136012
After xsr.nextTag() read QName, from there you can get tag name and prefix
QName qname = xsr.getName();
String pref = qname.getPrefix();
String name = qname.getLocalPart();
Upvotes: 1