1 <?xml version="1.0" encoding="UTF-8" ?> 2 <students> 3 <student number="itcast_0001"> 4 <!--<name id="itcast">tom</name>--> 5 <name id="itcast"> 6 <xing>张</xing> 7 <ming>三</ming> 8 </name> 9 <age>9999</age> 10 <sex>male</sex> 11 </student> 12 <student number="itcast_0002"> 13 <name>sam</name> 14 <age>20</age> 15 <sex>female</sex> 16 </student> 17 </students>
1 package com.haifei.jsoup; 2 3 import org.jsoup.Jsoup; 4 import org.jsoup.nodes.Document; 5 import org.jsoup.nodes.Element; 6 import org.jsoup.select.Elements; 7 8 import java.io.File; 9 import java.io.IOException; 10 11 /** 12 * Jsoup快速入门 13 * 14 * 步骤: 15 * 1. 导入jar包 16 * 2. 获取Document对象 17 * 3. 获取对应的标签Element对象 18 * 4. 获取数据 19 */ 20 public class JsoupDemo1 { 21 public static void main(String[] args) throws IOException { 22 // 2.获取Document对象,根据xml文档获取 23 // 2.1获取student.xml的path 24 // String path = JsoupDemo1.class.getClassLoader().getResource("..//dtd/student.xml").getPath(); 25 String path = JsoupDemo1.class.getClassLoader().getResource("student.xml").getPath(); 26 // 2.2解析xml文档,加载文档进内存,获取dom树(Document对象) 27 Document document = Jsoup.parse(new File(path), "utf-8"); 28 29 // 3.获取元素(标签)对象Element 30 Elements elements = document.getElementsByTag("name"); //是一个arraylist集合 31 System.out.println(elements.size()); //2 32 // 3.1获取第一个name的Element对象 33 Element element = elements.get(0); 34 35 // 4获取数据 36 String name = element.text(); 37 System.out.println(name); //tom 38 } 39 }