处理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);
}