您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
13_xml_解析_Jsoup_Element对象
发布时间:2022-07-29 21:52:17编辑:雪饮阅读()
基于上篇,本篇主要是了解下Jsoup中Element对象的使用,拿到该对象后可以继续通过该对象获取子Element对象也或者获取Element对象的属性attr或文本节点或html节点。则具体如:
quickIntroduction.java:
package day12;
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.net.URL;
public class quickIntroduction {
public static void main(String[] args) throws Exception{
getElement();
}
public static void getElement() throws Exception{
String path=quickIntroduction.class.getClassLoader().getResource("day12/test5.xml").getPath();
Document document= Jsoup.parse(new File(path),"utf-8");
Element element=document.getElementsByTag("user").get(0);
System.out.println("-------------获取Element---------------");
System.out.println(element);
System.out.println("-------------进一步可还可以通过Element对象获取子Element列表---------------");
Elements names=element.getElementsByTag("name");
System.out.println(names.size());
System.out.println("-------------还可以通过Element对象获取该Element的指定属性的值---------------");
System.out.println(element.attr("number"));
System.out.println("-------------还可以通过Element对象获取该Element的文本节点---------------");
System.out.println(names.get(0).text());
System.out.println("-------------还可以通过Element对象获取该Element的html节点---------------");
System.out.println(names.get(0).html());
System.out.println("-------------上面可以看到通过Element对象获取的text文本节点和html节点内容是一致的,那是因为正好name节点是最终节点,下面没有子节点了,下面这个例子则获取的html节点就是字符串形式的标签咯---------------");
System.out.println(document.getElementsByTag("user").get(1).html());
System.out.println("-------------也就是说通过Element对象获取的html节点只有在该Element节点下面还有子节点时候才有用,且该子节点不是text节点哦---------------");
}
}
关键字词:xml,解析,Jsoup,Element,对象