?xml version= 1.0 encoding= UTF-8 ?
students
student number= heima_0001
name id= 1
xing wu /xing
ming di /ming
/name
age name= xiaoer 19 /age
sex male /sex
/student
student number= heima_0002
name wudi /name
age 19 /age
sex male /sex
/student
/students
package cn.itcast.xml.jsoup;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import cn.wanghaomiao.xpath.exception.XpathSyntaxErrorException;
import cn.wanghaomiao.xpath.model.JXDocument;
import cn.wanghaomiao.xpath.model.JXNode;
/*
* Jsoup快速入门
*/
public class JsoupDemo6 {
public static void main(String[] args) throws IOException, XpathSyntaxErrorException {
//2.获取Document对象(是要基于xml文档才可以获取的)
//根据xml文档来获取
//2.1获取student.xml的path
String path=JsoupDemo6.class.getClassLoader().getResource( student.xml ).getPath();
//2.2解析xml文档,加载文档进内存,获取dom树(也就获取到了document对象)
Document document = Jsoup.parse(new File(path), utf-8 //字符集和文本的字符集一致
//3.根据document对象,创建JXDocument对象
JXDocument jxDocument=new JXDocument(document);
//4.结合Xpath语法来查询了
//4.1查询所有的student标签
List JXNode jxNodes = jxDocument.selN( //student
for (JXNode jxNode : jxNodes) {
System.out.println(jxNode);
}
System.out.println( ===============
//4.2查询所有student标签下的name标签
List JXNode jxNodes2 = jxDocument.selN( //student/name
for (JXNode jxNode : jxNodes2) {
System.out.println(jxNode);
}
System.out.println( ===============
//4.3查询student标签下带有id属性的name标签
List JXNode jxNodes3 = jxDocument.selN( //student/name[@id]
for (JXNode jxNode : jxNodes3) {
System.out.println(jxNode);
}
System.out.println( ===============
//4.4查询student标签下带有id属性的name标签并且id的属性值为1
List JXNode jxNodes4 = jxDocument.selN( //student/name[@id= 1 ]
for (JXNode jxNode : jxNodes4) {
System.out.println(jxNode);
}
}
}