解码SOAP Envelope时遇到问题。 这是我的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>
我使用以下代码对主体进行解码,但它总是返回命名空间tns:MessageID,而不是env:body。我还想将XMLStreamReader转换为字符串以进行调试问题,是否可能?
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
答案 0 :(得分:1)
在xsr.nextTag()读取QName后,您可以从那里获取标签名称和前缀
QName qname = xsr.getName();
String pref = qname.getPrefix();
String name = qname.getLocalPart();
答案 1 :(得分:1)
最初xsr指向文档事件之前(即XML声明),nextTag()
前进到下一个标记,而不是下一个兄弟元素:
xsr.nextTag(); // Advance to opening envelope tag
xsr.nextTag(); // advance to opening header tag
xsr.nextTag(); // advance to opening MessageId
如果你想跳到身体,一个更好的习语是
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
}
}