xml_解析_Jsoup_根据选择器查询
快捷查询方式:
selector:选择器
使用的方法:Element: select(String cssQuery)
语法:参考Selector类中定义的语法
public class JsoupDemo5 { public static void main(String[] args) throws IOException { //1.获取student.xml的path String path = JsoupDemo5.class.getClassLoader().getResource("student.xml").getPath(); //2.获取Document对象 Document document = Jsoup.parse(new File(path), "utf-8"); //Elements select(String cssQuery); //查询name标签 Elements name = document.select("name"); System.out.println(name); System.out.println("------------------"); //查询id值为1的元素 Elements select = document.select("#1"); System.out.println(select); System.out.println("------------------"); //获取student标签并且number属性值为aaa_0001的age子标签 //获取student标签并且number属性值为aaa_0001 Elements select1 = document.select("student[number='aaa_0001']"); System.out.println(select1); System.out.println("------------------"); //获取student标签并且number属性值为aaa_0001的age子标签 Elements age = select1.select("student[number='aaa_0001']>age"); System.out.println(age); } }
xml_解析_Jsoup_根据Xpath查询
XPath:XPath即为XML路径语言(XML Path Language),它是一种用来确定XML文档中某部分位置的语言
使用Jsoup的Xpath需要额外导入jar包:JsoupXpath-0.3.2.jar
查询w3cschool参考手册,使用xpath的语法完成查询
public class JsoupDemo6 { public static void main(String[] args) throws IOException, XpathSyntaxErrorException { //1.获取student.xml的path String path = JsoupDemo6.class.getClassLoader().getResource("student.xml").getPath(); //2.获取Document对象 Document document = Jsoup.parse(new File(path), "utf-8"); /** * 根据Xpath查询 */ //根据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("--------------------"); //查询所有的student标签下的name标签 List<JXNode> jxNodes1 = jxDocument.selN("//student/name"); for (JXNode jxNode : jxNodes1) { System.out.println(jxNode); } System.out.println("--------------------"); //查询所有的student标签下带有id属性的name标签 List<JXNode> jxNodes2 = jxDocument.selN("//student/name[@id]"); for (JXNode jxNode : jxNodes2) { System.out.println(jxNode); } System.out.println("--------------------"); //查询所有的student标签下带有id属性的name标签标签id属性值为1 List<JXNode> jxNodes3 = jxDocument.selN("//student/name[@id='1']"); for (JXNode jxNode : jxNodes3) { System.out.println(jxNode); } System.out.println("--------------------"); } }
标签:xml,标签,System,查询,student,println,选择器,out From: https://www.cnblogs.com/qihaokuan/p/16936205.html