【问题标题】:XMLStreamReader and UnMarshalling a SOAP MessageXMLStreamReader 和解组 SOAP 消息
【发布时间】:2013-04-04 14:02:00
【问题描述】:

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

【问题讨论】:

    标签: java xml soap xml-parsing


    【解决方案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
      }
    }
    

    【讨论】:

    • 我得到了异常 [com.sun.istack.internal.SAXParseException2;行号:6;列号:3;意外元素(uri:“w3.org/2003/05/soap-envelope”,本地:“Body”)。我想读一下身体“之后”是什么,以便我可以解开它
    • @AhmedSaleh 一旦你找到了开头的Body 标签then你可以使用一次xsr.nextTag() 以便前进到正文中元素的开头标签,并从那里开始解组。
    【解决方案2】:

    xsr.nextTag() 读取 QName 后,可以从那里得到标签名和前缀

    QName qname = xsr.getName();
    String pref = qname.getPrefix();
    String name = qname.getLocalPart();
    

    【讨论】:

      猜你喜欢
      • 2011-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-29
      • 2012-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多