jsoup解析的常见用法

1、解析attribute中值,如下面所示的serviceID和serviceName:

String str="如下所示";




解析方法:

 

List> resultList = new ArrayList>();
org.jsoup.nodes.Document doc = Jsoup.parse(str);
org.jsoup.select.Elements links = doc.getElementsByTag("Item");
for(int i=0;i map = new HashMap();
    map.put("serviceid", links.get(i).attr("serviceid"));
    map.put("serviceName", links.get(i).attr("serviceName"));
    resultList.add(map);
}
 

2、解析xml节点值

String str="如下所示";




201203210001
xxx
20110824
xxx
xxxxxx



201203210002
xxx
20110824
xxx
xxxxxx

 

解析方法:

List> resultList = new ArrayList>();
org.jsoup.nodes.Document doc = Jsoup.parse(str);
org.jsoup.select.Elements links_id = doc.getElementsByTag("ID");
org.jsoup.select.Elements links_title = doc.getElementsByTag("TITLE");
org.jsoup.select.Elements links_date = doc.getElementsByTag("RELEASE_DATE");
org.jsoup.select.Elements links_source = doc.getElementsByTag("SOURCE");
org.jsoup.select.Elements links_content = doc.getElementsByTag("CONTENT");
for(int i = 0;i resultMap = new HashMap();
	resultMap.put("id", links_id.get(i).text());
	resultMap.put("title", links_title.get(i).text());
	resultMap.put("relDate", links_date.get(i).text());
	resultMap.put("source", links_source.get(i).text());
	resultMap.put("content", links_content.get(i).text());
	resultList.add(resultMap);
}

3、解析html
1>根据"td"或者"tr"来解析
     org.jsoup.nodes.Document doc = Jsoup.parse(resHtml);
     org.jsoup.select.Elements links = doc.getElementsByTag("td");
     循环获取td中的值:
     links.get(i).text();

2>根据"class"参数来解析,如

...
     org.jsoup.nodes.Document doc = Jsoup.parse(resHtml);
     org.jsoup.select.Elements links = doc.select(".jtpsoft");
     然后根据links里面的 td或者tr标签来解析

3>根据 "name"参数来解析
    org.jsoup.nodes.Document doc = Jsoup.parse(resHtml);
    org.jsoup.select.Elements _links1 = doc.select("[name=zgzh]");
    org.jsoup.select.Elements _links2= doc.select("[name=sfzh]");
    如有多个name参数相同的值,则循环输出 _links1.get(i).val();
    取第一个值也可以使用_links1.first().val();

有兴趣的同学可以参考 http://jsoup.org/cookbook/

 

你可能感兴趣的:(应用开发)