2

我在解码 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
4

2 回答 2

1

在 xsr.nextTag() 读取 QName 后,您可以从那里获取标签名称和前缀

QName qname = xsr.getName();
String pref = qname.getPrefix();
String name = qname.getLocalPart();
于 2013-04-04T14:18:53.840 回答
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
  }
}
于 2013-04-04T14:22:34.017 回答