maven中引入Jsoup
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.9.2</version>
</dependency>
不同形式获取Document
//获取远程url
String url = "https://angular.cn/docs/ts/latest/guide/animations.html";
Document doc = Jsoup.connect(url).get();
//获取本地文件
File file = new File("G:/test.xml");
Document doc = Jsoup.parse(file, "UTF-8");
//直接解析字符串
String html="<html></html>";
Document doc = Jsoup.parse(html);
标签查找
//1. 查找指定标签名的标签
String path = "G:/test.xml";
File file = new File(path);
Document doc;
doc = Jsoup.parse(file, "UTF-8");
Elements es = doc.select("pro");
for (int i = 0; i < es.size(); i++) {
System.out.println(es.get(i));
}
//2.查看标签中的文本内容
System.out.println(es.get(i).html());
属性查找
//1. 查找包含某属性名的标签
Elements es = doc.getElementsByAttribute("name");
或
Elements es = doc.select("[name]");
//2. 查找以某属性名开头的标签
Elements es = doc.getElementsByAttributeStarting("nam");
//3. 查找属性与值匹配的标签
Elements es = doc.getElementsByAttributeValue("name", "mypro");
或
Elements es = doc.select("[name=mypro]");
//4. 查找name属性的属性值包含mypro的标签
Elements es = doc.getElementsByAttributeValueContaining("name", "mypro");
或
Elements es = doc.select("[name~=mypro]");
//5. 查找含某类属性标签
Elements es = doc.getElementsByClass("mycss");
联合查询
//1. 查找pro标签带class属性的标签
Elements es = doc.select("pro").select("[class]");
内容插入
//1. 在标签后插入
Elements es = doc.select("pro");
es.last().after("哈哈");
//2. 在标签中插入
es.last().append("哈哈");
//3. 在标签前插入
es.last().before("哈哈");
//4. 标签中插入文档中的标签
es.last().after(doc.select("pro").select("[name=mypro]").outerHtml());
网友评论