java - 面临问题 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”方法。
解决方案
推荐阅读
- ruby-on-rails - 如何使用 Rails 在 MongoDB 中验证跨模型的唯一性?
- ffmpeg - WAV 文件上的 Google Speech to Text 提供
- python - 你能看到一个进程是否是_alive,没有它先加入?
- html - 无法减小 flexbox 容器中的元素大小并对齐项目
- java - 在 GraalVM 本机映像中使用 Google Api 服务时出现“无效的 JWT:受众检查失败”
- javascript - 如何使用 React 和 Redux 制作预加载器?
- python - 在 PYTHON 中,如何关联数据框中的值以将它们都传递给 SQL 更新?
- react-native - 反应原生 react-native-google-places-autocomplete VirtualizedLists 警告
- pandas - Excel 计算列中是否包含在行中
- javascript - JavaScript:试图创建一个行为良好的后台作业,但在系统其余部分大部分空闲时运行时间太少?