gpt4 book ai didi

java - XMLStreamReader 和解码 SOAP 消息

转载 作者:行者123 更新时间:2023-11-30 09:24:12 25 4
gpt4 key购买 nike

解码 SOAP 信封时遇到问题。这是我的 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

最佳答案

最初 xsr 指向文档事件之前(即 XML 声明),并且 nextTag() 前进到下一个 tag,而不是下一个兄弟 元素:

    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
}
}

关于java - XMLStreamReader 和解码 SOAP 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15813467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com