使用Jsoup解析xml
例子
xml文档
<?xml version="1.0" encoding="UTF-8" ?>
<students>
<student number="heima_001">
<name>tom</name>
<age>18</age>
<sex>male</sex>
</student>
<student number="heima_002" id="sun">
<name>jack</name>
<age>18</age>
<sex>male</sex>
</student>
</students>
java文件
package cn.itcast.xml.jsop;
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;
public class JsoupDemo {
public static void main(String[] args) throws IOException {
//获取xml文件的路径
String path = Jsoup.class.getClassLoader().getResource("student.xml").getPath();
//解析xml
Document document = Jsoup.parse(new File(path), "utf-8");
//获取节点
Elements elements = document.getElementsByTag("name");
//System.out.println(elements);
Element element = elements.get(0);
//获取元素节点的文本
String name = element.text();
System.out.println(name);
//使用selector快速获取元素
Elements elements = document.select("#sun");
System.out.println(elements);
System.out.println("----------------");
Elements elements1 = document.select("student[number=\"heima_001\"]");
System.out.println(elements1);
//使用Xpath快速获取元素
}
}
输出结果
tom
<student number="heima_002" id="sun">
<name>
jack
</name>
<age>
18
</age>
<sex>
male
</sex>
</student>
----------------
<student number="heima_001">
<name>
tom
</name>
<age>
18
</age>
<sex>
male
</sex>
</student>