首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >XMLStreamReader和UnMarshalling一条SOAP消息

XMLStreamReader和UnMarshalling一条SOAP消息
EN

Stack Overflow用户
提问于 2013-04-04 22:02:00
回答 2查看 2.5K关注 0票数 2

解码SOAP信封时遇到问题。下面是我的XML

代码语言:javascript
复制
<?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>

我使用以下代码来解码body,但它总是返回到名称空间tns:MessageID,而不是env:body。我还想将XMLStreamReader转换为字符串以解决调试问题,这是可能的吗?

代码语言:javascript
复制
   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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-04-04 22:22:34

最初,xsr在文档事件(即XML声明)之前指向,nextTag()前进到下一个标记,而不是下一个同级元素

代码语言:javascript
复制
    xsr.nextTag(); // Advance to opening envelope tag
    xsr.nextTag(); // advance to opening header tag
    xsr.nextTag(); // advance to opening MessageId

如果你想跳过正文,一个更好的习惯用法应该是

代码语言:javascript
复制
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
  }
}
票数 1
EN

Stack Overflow用户

发布于 2013-04-04 22:18:54

在xsr.nextTag()读取QName之后,您可以从中获得标记名和前缀

代码语言:javascript
复制
QName qname = xsr.getName();
String pref = qname.getPrefix();
String name = qname.getLocalPart();
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15813467

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档