dom4j--XPath获取特定节点应用一例
<?xml version="1.0" encoding="GBK"?><chat> <messages> <from>[系统公告]</from> <face/> <to/> <content><font color='gray'>叶明坚同同学走进了聊天室!</font></content> <sendTime>2010-8-21 13:02:17</sendTime> <isPrivate>false</isPrivate> </messages> <messages> <from>叶明坚同同学</from> <face>正义凛然的</face> <to>所有人</to> <content><font color='>哈哈,陈步青同同学终于解决了中文乱码问题啦¥%#@%</font></content> <sendTime>2010-8-21 13:03:00</sendTime> <isPrivate>false</isPrivate> </messages> <messages> <from>[系统公告]</from> <face/> <to/> <content><font color='gray'>陈步青走进了聊天室!</font></content> <sendTime>2010-8-21 13:05:54</sendTime> <isPrivate>false</isPrivate> </messages> <messages> <from>陈步青</from> <face>微笑着</face> <to>叶明坚同同学</to> <content><font color='>告诉你个秘密,我终于解决了那个烦人的中文乱码问题啦</font></content> <sendTime>2010-8-21 13:06:40</sendTime> <isPrivate>true</isPrivate> </messages> <messages> <from>[系统公告]</from> <face/> <to/> <content><font color='gray'>小牛顿走进了聊天室!</font></content> <sendTime>2010-8-21 21:29:25</sendTime> <isPrivate>false</isPrivate> </messages> <messages> <from>[系统公告]</from> <face/> <to/> <content><font color='gray'>陈步青走进了聊天室!</font></content> <sendTime>2010-8-21 21:29:51</sendTime> <isPrivate>false</isPrivate> </messages> <messages> <from>[系统公告]</from> <face/> <to/> <content><font color='gray'>hak走进了聊天室!</font></content> <sendTime>2010-8-21 21:31:40</sendTime> <isPrivate>false</isPrivate> </messages> <messages> <from>小牛顿</from> <face>严肃的</face> <to>所有人</to> <content><font color='>大家一起吹水。。。。</font></content> <sendTime>2010-8-21 21:32:54</sendTime> <isPrivate>false</isPrivate> </messages> <messages> <from>[系统公告]</from> <face/> <to/> <content><font color='gray'>蔡泽鑫走进了聊天室!</font></content> <sendTime>2010-8-21 22:40:05</sendTime> <isPrivate>false</isPrivate> </messages> </chat>?java代码:
package scau.netbeansTester;import java.util.Iterator;import java.util.List;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.Node;import org.dom4j.io.SAXReader;public class TestRootE {/** * @param args * @throws DocumentException */public static void main(String[] args) throws DocumentException {// TODO Auto-generated method stubSAXReader reader = new SAXReader(); Document document = null; document = reader.read("TestRootE.xml"); //获取指定目录下的所有<messages>节点 List<Node> list = (List<Node>)document.selectNodes("//chat/messages"); //依次取出每个<messages>节点 for(Node n : list) {Element messagesElement = (Element) n;//取得每个<messages>节点下名为"sendTime"的节点 String sendTime = messagesElement.element("sendTime").getText(); p(sendTime);} }public static void p(Object o ) {System.out.println(o);}}?