xml解析Jsoup根据选择器查询和xmlJsoup根据Xpath查询
xml解析Jsoup根据选择器查询
selector:选择器
使用的方法:Elements select(String cssQuery)
/* 选择器查询 */ private static void xuanze() throws IOException{ //获取student.xml的path String path = Jsoup_3_Document.class.getClassLoader().getResource("student.xml").getPath(); //获取Document对象 Document document = Jsoup.parse(new File(path), "utf-8"); //3.查询name标签 Elements elements = document.select("name"); System.out.println(elements); System.out.println("======================="); //查询id值为itcast的元素 Elements elements1 = document.select("#itcast"); System.out.println(elements1); System.out.println("======================="); //获取student标签并且number属性值为sq_0001的age子标签 Elements elements2 = document.select("student[number=\"sq_0001\"] > age"); System.out.println(elements2); }
xmlJsoup根据Xpath查询
XPath即为XML路径语言(XML Path Language),它是一种用来确定XML(标准通用标记语言的子集)文档中某部分位置的语言
使用Jsoup的Xpath需要额外导入jar包 JsoupXpath-0.3.2.jar
查询w3cshool参考手册,使用xpath的语法完成查询
/* Xpath查询 */ private static void XPathq() throws IOException, XpathSyntaxErrorException { //获取student.xml的path String path = Jsoup_3_Document.class.getClassLoader().getResource("student.xml").getPath(); //获取Document对象 Document document = Jsoup.parse(new File(path), "utf-8"); //根据document对象,创建JXDocument对象 JXDocument jxDocument = new JXDocument(document); //结合xpath语法查询 //查询所有的student标签 List<JXNode> jxNodes = jxDocument.selN("//student"); for (JXNode jxNode : jxNodes) { System.out.println(jxNode); } System.out.println("================================"); List<JXNode> jxNodes2 = jxDocument.selN("//student/name"); for (JXNode jxNode2 : jxNodes2) { System.out.println(jxNode2); } System.out.println("================================"); //查询student标签下带有id属性的name标签 List<JXNode> jxNodes3 = jxDocument.selN("//student/name[@id]"); for (JXNode jxNode3 : jxNodes3) { System.out.println(jxNode3); } System.out.println("================================"); //查询student标签下带有id属性的name标签,并且id属性值为itcast List<JXNode> jxNodes4 = jxDocument.selN("//student/name[@id]"); for (JXNode jxNode4 : jxNodes4) { System.out.println(jxNode4); } }