第一种方法遍历Dom树,不使用xpath
Element re=document.getRootElement();
List es=re.elements("entry");
for(int i=0;i
List list = document.selectNodes("//item");
for (Iterator iter = list.iterator(); iter.hasNext(); ) {
Node currentItem=(Node)iter.next();
Element title=(Element)currentItem.selectSingleNode("./title");
Element link=(Element)currentItem.selectSingleNode("./link");
Element pubDate=(Element)currentItem.selectSingleNode("./pubDate");
Element description=(Element)currentItem.selectSingleNode("./description");
}
xmlns="http://www.w3.org/2005/Atom"
所以需要在解析时先创建名称空间,或者在使用xpath的元素上注册或添加名称空间:
Map uris = new HashMap();
uris.put("atom", "http://www.w3.org/2005/Atom");
XPath xpath = document.createXPath("/atom:feed/atom:entry");
xpath.setNamespaceURIs(uris);
List list = xpath.selectNodes(document);
for (Iterator iter = list.iterator(); iter.hasNext(); ) {
Element currentItem=(Element)iter.next();
Element title=(Element)currentItem.selectSingleNode("./title");
Element link=(Element)currentItem.selectSingleNode("./link");
Element pubDate=(Element)currentItem.selectSingleNode("./updated");
Element description=(Element)currentItem.selectSingleNode("./content");
}
Element title=(Element)currentItem.selectSingleNode("./atom:title");
Element link=(Element)currentItem.selectSingleNode("./atom:link");
Element updated=(Element)currentItem.selectSingleNode("./atom:updated");
Element content=(Element)currentItem.selectSingleNode("./atom:content");
public Element addNamespace(String prefix, String uri)
currentItem.addNamespace("atom", "http://www.w3.org/2005/Atom");
本文使用的dom4j是1.6.1,如果在你用的版本中使用上述代码有错误,请仔细阅读文档