jsoup解析的常見用法

一、解析attribute中值,以下面所示的serviceID和serviceName:html

String str="以下所示";java

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

解析方法:spa

 

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);  
}

 

二、解析xml節點值code

String str="以下所示";xml

<?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>htm

 

解析方法:utf-8

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);  
}



三、解析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();get

相關文章
相關標籤/搜索