【问题标题】:Get SOAP element by tag with namespace in Java在Java中通过标签获取SOAP元素与命名空间
【发布时间】:2017-02-14 06:30:14
【问题描述】:

我想知道当子标签看起来像这样时,如何获取 SOAP 响应主体子的内容:

<sth:x>...</sth:x>

在 Oracle 文档中,我找到了 loop all Elements with a specific name 的方法。 但因此我需要先创建一个元素来指定我要搜索的标签的名称。

如何创建一个看起来像上面的元素?我知道怎么做这样的:

<sth:id sth="asdf">

但这并没有真正起作用。 这是我尝试阅读的服务器响应。

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <soapenv:Header/>
    <soapenv:Body>
        <ns5:loginResponse xmlns:ns5="x">
            <ns5:id>Value I am looking for</ns5:id>
            <ns5:rc>0</ns5:rc>
        </ns5:loginResponse>
     </soapenv:Body>
</soapenv:Envelope>

感谢您的帮助:)

【问题讨论】:

    标签: java soap


    【解决方案1】:

    试试这个:

    String xml = "YourXMl";
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(xml));
    Document doc = builder.parse(is);
    NodeList nodes =  doc.getDocumentElement().getElementsByTagNameNS("x","id");
    System.err.println(nodes.item(0).getChildNodes().item(0).getNodeValue());
    

    有两个重要的事情factory.setNamespaceAware(true); - 打开对 xml 命名空间的支持。 doc.getDocumentElement().getElementsByTagNameNS("x","id"); 使用命名空间 uri 和元素名称获取元素。这里是命名空间 uri 的 &lt;ns5:loginResponse xmlns:ns5="x"&gt; 声明。 x 是 uri ns5 是命名空间。

    【讨论】:

    • 我试过了,但我得到了以下错误:org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog. 另外你知道使用 SOAP API 读取答案的方法吗?
    【解决方案2】:

    我找到了答案:

    有问题的元素在另一个 SOAPBodyElement 中。 所以循环遍历这两个元素给了我正确的值:

    body = reply.getSOAPBody();
    Iterator replyIt = body.getChildElements();
    
    while(replyIt.hasNext()){
        SOAPBodyElement replysbe = (SOAPBodyElement) replyIt.next();
        Iterator replyIt2 = replysbe.getChildElements();
        SOAPElement sentSE = (SOAPElement) replyIt2.next();
        sessionID = sentSE.getValue();
    }
    

    【讨论】:

      猜你喜欢
      • 2015-11-30
      • 1970-01-01
      • 2013-08-27
      • 1970-01-01
      • 2017-04-25
      • 1970-01-01
      • 1970-01-01
      • 2017-05-07
      • 2013-08-07
      相关资源
      最近更新 更多