运行代码出现Exception in thread "main" java.lang.NullPointerException
JsoupDemo1.java代码如下:
package study.java.xml.jsoup;
/*
* 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;
public class JsoupDemo1 {
public static void main(String[] args) throws IOException {
//2.1获取student.xml的path
String path = JsoupDemo1.class.getClassLoader().getResource("src\\student.xml").getPath();
//上面的student.xml是已经写好的xml文件
//2.2解析xml文档,加载文档进内存,获取dom树--->Document
Document document = Jsoup.parse(new File(path), "UTF-8");
//3.获取xml文档里面的元素标签对象 Element-----name
Elements elements = document.getElementsByTag("name");
System.out.println(elements.size());
//3.1获取第一个name的Element对象
Element element = elements.get(0);
//3.2获取数据
String name = element.text();
System.out.println(name);
}
}
student.xml代码如下:
<?xml version="1.0" encoding="UTF-8" ?>
<students>
<student number="heima_0001">
<name>zhangsan</name>
<age>11</age>
<sex>male</sex>
</student>
<student number="heima_0002">
<name>lisi</name>
<age>44</age>
<sex>female</sex>
</student>
</students>