JavaWeb / Fore_End /XML /src /cn /itcast /xml /jsoup /JsoupDemo6.java
zxy0307's picture
Upload 3493 files
08aee07 verified
Raw History Blame Contribute Delete
2.13 kB
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 java.io.File;
import java.io.IOException;
import java.util.List;
/**
* 快速查询方式:2、XPath
*/
public class JsoupDemo6 {
public static void main(String[] args) throws IOException, XpathSyntaxErrorException {
/*
2. XPath:XPath即为XML路径语言,它是一种用来确定XML(标准通用标记语言的子集)文档中某部分位置的语言
* 使用Jsoup的Xpath需要额外导入jar包。
*/
//1、获取document对象
String path = JsoupDemo6.class.getClassLoader().getResource("student1.xml").getPath();
Document document = Jsoup.parse(new File(path), "utf-8");
//2、根据document对象,创建JXDocument对象
JXDocument jxDocument = new JXDocument(document);
//3、结合XPath语法查询 -- 查询所有student标签 //student
List<JXNode> jxNodes = jxDocument.selN("//student");
for (JXNode jxNode : jxNodes) {
System.out.println(jxNode);
}
System.out.println("=======================");
//4、查询所有student下的 name标签
List<JXNode> jxNodes2 = jxDocument.selN("//student/name");
for (JXNode jxNode : jxNodes2) {
System.out.println(jxNode);
}
System.out.println("=======================");
//5、查询student下的,带有id的name标签
List<JXNode> jxNodes3 = jxDocument.selN("//student/name[@id]");
for (JXNode jxNode : jxNodes3) {
System.out.println(jxNode);
}
System.out.println("=======================");
//6、查询student下的,id为1的name标签
List<JXNode> jxNodes4 = jxDocument.selN("//student/name[@id='1']");
for (JXNode jxNode : jxNodes4) {
System.out.println(jxNode);
}
System.out.println("=======================");
}
}