jsoup解析的常见用法

原创
2015/12/11 09:53
阅读数 164

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

String str="如下所示";

<Root>
<Item serviceID="16" serviceName="住家保姆" />
<Item serviceID="17" serviceName="不住家保姆" />
</Root>

解析方法:

 

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

 

2、解析xml节点值

String str="如下所示";

<?xml version="1.0" encoding="utf-8"?>
<data>
<ITEM>
<ID>201203210001</ID>
<TITLE>xxx</TITLE>
<RELEASE_DATE>20110824</RELEASE_DATE>
<SOURCE>xxx</SOURCE>
<CONTENT>xxxxxx</CONTENT>
</ITEM>

<ITEM>
<ID>201203210002</ID>
<TITLE>xxx</TITLE>
<RELEASE_DATE>20110824</RELEASE_DATE>
<SOURCE>xxx</SOURCE>
<CONTENT>xxxxxx</CONTENT>
</ITEM>
</data>

 

解析方法:

List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();  
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<links_id.size();i++){  
    Map<String, Object> resultMap = new HashMap<String, Object>();  
    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"参数来解析,如 <div class=".jtpsoft">...
     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();

展开阅读全文
加载中

作者的其它热门文章

打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部