如何使用XPath提取xml文档数据
本文实例为大家分享了XPath提取xml文档数据具体代码,供大家参考,具体内容如下
importjava.util.List; importorg.dom4j.Document; importorg.dom4j.Node; importorg.dom4j.io.SAXReader; importorg.junit.Test; /* *使用XPath查找xml文档数据 * */ publicclassDemoXPath{ @Test //输出book.xml中所有price元素节点的文本值 publicvoidtest1()throwsException{ SAXReaderreader=newSAXReader(); Documentdocument=reader.read("src/main/java/book.xml"); ListselectNodes=document.selectNodes("//price"); for(Nodenode:selectNodes){ Stringtext=node.getText(); System.out.println(text); } } @Test //输出book.xml中第二本书的price元素节点的文本值 publicvoidtest2()throwsException{ SAXReaderreader=newSAXReader(); Documentdocument=reader.read("src/main/java/book.xml"); NodeselectSingleNode=document.selectSingleNode("/bookshelf/book[2]/price"); Stringtext=selectSingleNode.getText(); System.out.println(text); } @Test //输出book.xml中第二本书和第三本书的author元素节点的文本值 publicvoidtest3()throwsException{ SAXReaderreader=newSAXReader(); Documentdocument=reader.read("src/main/java/book.xml"); ListselectSingleNode=document.selectNodes("/bookshelf/book[position()>1]/author"); for(Nodenode:selectSingleNode){ Stringtext=node.getText(); System.out.println(text); } } @Test //输出book.xml中含有属性id的所有name的文本值 publicvoidtest4()throwsException{ SAXReaderreader=newSAXReader(); Documentdocument=reader.read("src/main/java/book.xml"); ListselectSingleNode=document.selectNodes("//name[@id]"); for(Nodenode:selectSingleNode){ Stringtext=node.getText(); System.out.println(text); } } @Test //输出book.xml中含有属性id="1111"的name的文本值 publicvoidtest5()throwsException{ SAXReaderreader=newSAXReader(); Documentdocument=reader.read("src/main/java/book.xml"); NodeselectSingleNode=document.selectSingleNode("//name[@id=\"1111\"]"); Stringtext=selectSingleNode.getText(); System.out.println(text); } @Test //输出book.xml中含有属性id="1112"的book的author的文本值 publicvoidtest6()throwsException{ SAXReaderreader=newSAXReader(); Documentdocument=reader.read("src/main/java/book.xml"); NodeselectSingleNode=document.selectSingleNode("//book[name[@id=\"1112\"]]/author"); Stringtext=selectSingleNode.getText(); System.out.println(text); } @Test //输出book.xml中第一本book的id的属性值 publicvoidtest7()throwsException{ SAXReaderreader=newSAXReader(); Documentdocument=reader.read("src/main/java/book.xml"); NodeselectSingleNode=document.selectSingleNode("//book[1]/name"); Stringtext=selectSingleNode.valueOf("attribute::id");//获取id属性 System.out.println(text); } @Test //输出book.xml中book的name的id的属性值为1112的对应的sn的属性值 publicvoidtest8()throwsException{ SAXReaderreader=newSAXReader(); Documentdocument=reader.read("src/main/java/book.xml"); ListselectNodes=document.selectNodes("//book/name"); for(Nodenode:selectNodes){ if(node.valueOf("attribute::id").equals("1112")){ System.out.println(node.valueOf("attribute::sn")); } } } }
junit junit 4.11 log4j log4j 1.2.17 dom4j dom4j jaxen jaxen 1.1.6
Tomorrow Hiskell $40 GoodbyetoYou Giddle $25 SeaandOld Heminw $28
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。