官方dom4举例
In dom4j XPath expressions can be evaluated on the Document or on any Node in the tree (such as Attribute, Element or ProcessingInstruction). This allows complex navigation throughout the document with a single line of code. For example. public void bar(Document document) { List list = document.selectNodes( "//foo/bar" ); Node node = document.selectSingleNode( "//foo/bar/author" ); String name = node.valueOf( "@name" ); } For example if you wish to find all the hypertext links in an XHTML document the following code would do the trick. public void findLinks(Document document) throws DocumentException { List list = document.selectNodes( "//a/@href" ); for (Iterator iter = list.iterator(); iter.hasNext(); ) { Attribute attribute = (Attribute) iter.next(); String url = attribute.getValue(); } } If you need any help learning the XPath language we highly recommend the Zvon tutorial which allows you to learn by example. |
举例
SAXReader reader=new SAXReader();
Document document=reader.read(new File("src/book.xml"));
String value=document.selectSingleNode("//作者").getText();//第一个值
System.out.println(value);
需要dom4j里面的额外jar包
Document document=reader.read(new File("src/book.xml"));
String value=document.selectSingleNode("//作者").getText();//第一个值
System.out.println(value);
需要dom4j里面的额外jar包
注意上述代码是错误的 XPath 表达式 是用的单引号