XPath表达式
什么是XPath
XPath:路徑表達式
作用:在DOM解析XML時,通過XPath表達讓解析更加簡單
XPath表達式分類
什么是Node對象
DOM樹中的每個節(jié)點就是Node
dom4j中與XPath相關(guān)的方法
注:使用XPath需要另外導入 jaxen-1.1.2.jar包
| Node selectSingleNode(String xpath) | 通過xpath得到一個節(jié)點 |
| List selectNodes(String xpath) | 通過xpath得到一組節(jié)點 |
XPath:絕對路徑和相對路徑
目標
絕對路徑語法
絕對路徑示例
需求
采用絕對路徑獲取從根節(jié)點開始逐層的查找/contactList/contact/name 節(jié)點列表并打印信息
步驟
代碼
public class Demo7Xpath {private Document document;//在每個測試方法之前執(zhí)行的方法@Beforepublic void init() throws DocumentException {//1. 得到SaxReaderSAXReader reader = new SAXReader();//2. 得到文檔對象document = reader.read(Demo7Xpath.class.getResourceAsStream("/Contact.xml"));}/**使用絕對路徑*/@Testpublic void testAbsolute() {String xpath = "/contactList/contact/name";//得到所有name元素List<Node> nodeList = document.selectNodes(xpath);for (Node node : nodeList) {System.out.println(node.getText());}} }相對路徑的語法
相對路徑的示例
需求
步驟
代碼
/**使用相對路徑*/ @Test public void testRelative() {//通過絕對路徑得到/contactListNode node = document.selectSingleNode("/contactList");//通過相對路徑得到nameNode nameNode = node.selectSingleNode("./contact/name");System.out.println(nameNode.getText()); }XPath:全文搜索和屬性查找
目標
學習XPath全文搜索的使用
學習XPath屬性查找的使用
舉例
| //contact | 找contact元素,無論元素在哪里 |
| //contact/name | 找contact,無論在哪一級,但name一定是contact的子節(jié)點 |
| //contact//name | contact無論在哪一種,name只要是contact的子孫元素都可以找到 |
全文搜索示例
需求
直接全文搜索所有的 name元素并打印
步驟
代碼
/**全文搜索*/ @Test public void testGlobalSearch() {List<Node> nodes = document.selectNodes("//name");for (Node node : nodes) {System.out.println(node.getText());} }屬性查找語法
屬性查找的示例
步驟
代碼
/**屬性查找*/ @Test public void testAttributeFind() {//1. 查找所有id屬性節(jié)點/*List<Node> nodes = document.selectNodes("//@id");//是屬性對象Attributefor (Node node : nodes) {//輸出屬性值Attribute a = (Attribute) node;System.out.println("屬性值:" + a.getValue());}*///2. 查找包括id屬性的contact元素/*List<Node> nodeList = document.selectNodes("//contact[@id]");for (Node node : nodeList) {System.out.println(node.getName());}*///3. 查找包括id屬性且屬性名為的contact元素Node node = document.selectSingleNode("//contact[@id=2]");System.out.println(node.getName()); }總結(jié)
- 上一篇: Golang——指针的使用、数组指针和指
- 下一篇: mysql innodb隔离级别_浅析M