查询xml的xpath时出现NullPointerException
,请帮我解决。
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”方法。