xml解析_Jsoup_根据选择器查询
快捷查询方式:
selector:选择器
使用的方法:Elements select(String cssQuery)
语法:参考Selector类中定义的语法
package cn.itcast.xml.jsoup; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.File; import java.io.IOException; /** *Element对象功能 */ 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 name = document.select("name"); System.out.println(name); System.out.println("====================="); //查询id值为itcast的元素 Elements select = document.select("#itcast"); System.out.println(select); System.out.println("====================="); //获取student标签并且number属性值为heima_0001的age子标签 //获取student标签并且number属性值为heima_0001 Elements select1 = document.select("student[number='heima_0001']"); System.out.println(select1); System.out.println("====================="); //获取student标签并且number属性值为heima_0001的age子标签 Elements select2 = document.select("student[number='heima_0001'] > age"); System.out.println(select2); } }
<?xml version="1.0" encoding="UTF-8" ?> <students> <student number="heima_0001"> <name id="itcast"> <xing>张</xing> <ming>三</ming> </name> <age>18</age> <sex>male</sex> </student> <student number="heima_0002"> <name>jack</name> <age>18</age> <sex>female</sex> </student> </students>
xml解析_Jsoup_根据Xpath查询
XPath:Xpath即为XML路径语言,它是一种用来确定XML(标准通用标记语言的子集)文档中某部分位置的语言
使用JSoup的Xpath需要额外导入jar包
查询w3cshool参考手册,使用xpath的语法完成查询
在libs包中导入jar包,添加为库
package cn.itcast.xml.jsoup; import cn.wanghaomiao.xpath.exception.XpathSyntaxErrorException; import cn.wanghaomiao.xpath.model.JXDocument; import cn.wanghaomiao.xpath.model.JXNode; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import java.io.File; import java.io.IOException; import java.util.List; /** *Element对象功能 */ 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"); //3.根据document对象,创建JXDocument对象 JXDocument jxDocument = new JXDocument(document); //4.集合Xpath语法查询 //查询所有student标签 List<JXNode> jxNodes = jxDocument.selN("//student"); for (JXNode jxNode : jxNodes) { System.out.println(jxNode); } System.out.println("=================="); List<JXNode> jxNodes1 = jxDocument.selN("//student/name"); for (JXNode jxNodes12 : jxNodes1) { System.out.println(jxNodes12); } System.out.println("=================="); List<JXNode> jxNodes2 = jxDocument.selN("//student/name[@id]"); for (JXNode jxNodes13 : jxNodes2) { System.out.println(jxNodes13); } } }标签:xml,System,查询,student,println,import,选择器,out From: https://www.cnblogs.com/wsfj/p/17081928.html