您的位置:首页 > 编程语言 > Java开发

Java XML 处理,命名空间,javax.xml

2014-09-15 15:17 465 查看
处理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);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: