利用xpath获取节点值实例
这几天做xml打包、解包的通用工具,学习了下xpath的使用方法,它可以很方便查询某一节点的值,有点类似于jquery的选择器,具体事例如下:
public String queryNodeValue(final Document doc, String expression)
throws XPathExpressionException {
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
xpath.setNamespaceContext(new NamespaceContext() {
@SuppressWarnings("rawtypes")
@Override
public Iterator getPrefixes(String namespaceURI) {
throw new UnsupportedOperationException();
}
@Override
public String getPrefix(String namespaceURI) {
throw new UnsupportedOperationException();
}
@Override
public String getNamespaceURI(String prefix) {
return doc.lookupNamespaceURI(prefix);
}
});
XPathExpression expr = xpath.compile(expression);
Object result = expr.evaluate(doc, XPathConstants.STRING);
return result == null ? null : result.toString();
}
上面是获取document的元素值的通用方法。