处理XML,最主要的是如果遇到了命名空间怎么办
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document document = dbf.newDocumentBuilder().parse(resourceAsStream);其中 setNamespaceAware(true) 就是处理命名空间的。
使用 xpath 来查找
public NodeList search(Document doc, String xpathString) throws XPathExpressionException {
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
final String myPrefix = "lg";
final String myUri = "urn:horizon:loggraphics";
xpath.setNamespaceContext(new NamespaceContext() {
public String getNamespaceURI(String prefix) {
return myPrefix.equals(prefix) ? myUri : null;
}
public String getPrefix(String namespaceURI) {
return null; // we are not using this.
}
public Iterator getPrefixes(String namespaceURI) {
return null; // we are not using this.
}
});
XPathExpression expression = xpath.compile(xpathString);
return (NodeList) expression.evaluate(doc, XPathConstants.NODESET);
}
本文介绍如何在Java中处理带有命名空间的XML文件。通过设置DocumentBuilderFactory的命名空间感知功能,并利用自定义的命名空间上下文解析XPath表达式,实现对特定命名空间下元素的有效检索。
2936

被折叠的 条评论
为什么被折叠?



