首页 > 解决方案 > 面临问题 java xml NamespaceContext

问题描述

我正在NullPointerException查询 xml 的 xpath,请帮我解决它。

XML:

<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
           xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
    <User xmlns="https://www.mycompany.com/">
        <PersoanlDetails>
            <Name>
                <FirstName>MyfirstName</FirstName>
                <MiddleName>MySecondName</MiddleName>
                <LastName>MyLastName</LastName>
            </Name>
        </PersoanlDetails>
    </User>
</soap:Body>
</soap:Envelope>

命名空间上下文:

public class MyNamespaceContext implements NamespaceContext {

    @Override
    public String getNamespaceURI(String prefix) {
        return XMLConstants.W3C_XML_SCHEMA_NS_URI; 
    }

    @Override
    public String getPrefix(String namespaceURI) {
        return null;
    }

    @Override
    public Iterator getPrefixes(String namespaceURI) {
        return null;
    }
}

传递 xpath 时返回元素对应字符串值的方法:

public String getElementValue(Document doc, NamespaceContext namespace, String xpathExpression) {
    try {
        doc.getDocumentElement().normalize();

        XPath xpath = XPathFactory.newInstance().newXPath();

        if (namespace != null)
            xpath.setNamespaceContext(namespace);

        Node node = (Node) xpath.compile(xpathExpression).evaluate(doc, XPathConstants.NODE);

        Element element = (Element) node;

        return element.getTextContent();
    } catch (XPathExpressionException ex) {
        ex.printStackTrace();
        return null;
    }
}

调用上述方法的代码:

//Document document -> i have an xml document parsed
String firstName = utilities.getElementValue(document, new MyNamespaceContext(), "//User/PersoanlDetails/Name/FirstName");

在“return element.getTextContent();”上获取 NullPointerException “getElementValue”方法。

标签: javaxmlnullpointerexception

解决方案


推荐阅读