File size: 2,331 Bytes
08aee07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package cn.itcast.xml.jsoup;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.File;
import java.io.IOException;
import java.net.URL;

/**
 * Jsoup对象功能
 */
public class JsoupDemo2 {
    public static void main(String[] args) throws IOException {
        String path = JsoupDemo2.class.getClassLoader().getResource("student1.xml").getPath();
        /*
            1. Jsoup:工具类,可以解析html或xml文档,返回Document
			    * parse:解析html或xml文档,返回Document
         */
        //1.1 parse(File in, String charsetName):解析xml或html文件的。
        Document document = Jsoup.parse(new File(path), "UTF-8");
        System.out.println(document);//打印xml的文件内容

        //1.2 parse(String html):解析xml或html字符串
        String xml = "<!--?xml version=\"1.0\" encoding=\"UTF-8\" ?-->\n" +
                "<html>\n" +
                " <head></head>\n" +
                " <body>\n" +
                "  <students> \n" +
                "   <student number=\"s001\"> \n" +
                "    <name>\n" +
                "     zhangsan\n" +
                "    </name> \n" +
                "    <age>\n" +
                "     abc\n" +
                "    </age> \n" +
                "    <sex>\n" +
                "     hehe\n" +
                "    </sex> \n" +
                "   </student> \n" +
                "   <student number=\"s002\"> \n" +
                "    <name>\n" +
                "     lisi\n" +
                "    </name> \n" +
                "    <age>\n" +
                "     24\n" +
                "    </age> \n" +
                "    <sex>\n" +
                "     female\n" +
                "    </sex> \n" +
                "   </student> \n" +
                "  </students>\n" +
                " </body>\n" +
                "</html>";
        Document document2 = Jsoup.parse(xml);
        System.out.println(document2);

        //1.3 parse(URL url, int timeoutMillis):通过网络路径获取指定的html或xml的文档对象
        URL url = new URL("https://www.baidu.com/baidu?tn=34046034_10_dg&ie=utf-8&wd=csdn");//代表网路中的一个资源路径
        Document document3 = Jsoup.parse(url, 3000);
        System.out.println(document3);//解析成HTML文档


    }
}