Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 无法分析具有不同命名空间的XML_Java_Xml_Xpath - Fatal编程技术网

Java 无法分析具有不同命名空间的XML

Java 无法分析具有不同命名空间的XML,java,xml,xpath,Java,Xml,Xpath,我有这样一个示例XML: <Envelope xmlns='http://schemas.xmlsoap.org/soap/envelope/'> <Header> </Header> <Body> <getNewTokenResponse xmlns="http://abc.examples.com/"> <return> {{

我有这样一个示例XML:

<Envelope xmlns='http://schemas.xmlsoap.org/soap/envelope/'>
    <Header>
    </Header>
    <Body>
        <getNewTokenResponse xmlns="http://abc.examples.com/">
            <return>
                {{session.key}}
            </return>
        </getNewTokenResponse>
    </Body>
</Envelope>
它没有返回正确的值,因为命名空间没有使用前缀


有更好的解析方法吗?

您应该使用
/s:Envelope/s:Body/p:getNewTokenResponse/p:return
作为XPath表达式,并提供一个将
s
映射到
http://schemas.xmlsoap.org/soap/envelope/
p
http://abc.examples.com/

XPath xpath = XPathFactory.newInstance().newXPath();
HashMap nsMap = getNameSpaceMap(input);
xpath.setNamespaceContext(new NamespaceContext() {
    @Override
    public String getNamespaceURI(String prefix) {
        if(nsMap.has(prefix)){
           return nsMap.get(prefix);
        }
        return XMLConstants.NULL_NS_URI;
    }

    @Override
    public String getPrefix(String namespaceURI) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Iterator getPrefixes(String namespaceURI) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
});

Node getNewTokenResp = 
     (Node) xpath.evaluate("/Envelope/Body/getNewTokenResponse/return", 
     document, XPathConstants.NODE);