2012-09-07 71 views
4

我是jsoup的新手,对html标记有点麻烦。我需要基于它们包含的文本来获取选择列表选项的值属性。例如:Jsoup访问HTML选择标记

'<select id="list"> 
<option value="0">First value</option> 
<option value="1">Second value</option> 
<option value="2">Third value</option> 
</select>' 

你有一个想法,我怎么能告诉jsoup返回值“1”,如果它得到了“二值”作为搜索参数?

回答

2

试试这个代码:

String searchValue = "Second value"; 
Elements options = doc.select("#list > option"); 
String value = ""; 
for (Element option : options) { 
    String text = option.text(); 
    if (text.equals(searchValue)){ 
     value = option.attr("value"); 
    } 
} 

希望它能帮助!

+0

感谢您的回复,但我没有得到任何抱歉... –

+0

代码中有编辑。现在就试试! – HashimR

+0

不,看起来它不会返回

5

这里的另一种解决方案:

public String searchAttribute(Element element, String str) 
{ 
    Elements lists = element.select("[id=list]"); 

    for(Element e : lists) 
    { 
     Elements result = e.select("option:contains(" + str + ")"); 

     if(!result.isEmpty()) 
     { 
      return result.first().attr("value"); 
     } 
    } 

    return null; 
} 

测试:

Document doc = Jsoup.parse(html); // html is your listed html/xml 
Strign result = searchAttribute(doc, "Second value") // result = 1 
6

这可以帮助你..

String demo = "<select id='list'><option value='0'>First value</option><option value='1'>Second value</option><option value='2'>Third value</option></select>"; 


     Document document = Jsoup.parse(demo); 
     Elements options = document.select("select > option"); 

     for(Element element : options) 
     { 
      if(element.text().equalsIgnoreCase("second value")) 
      { 
       System.out.println(element.attr("value")); 
      } 

     } 
1

我认为最简单的解决方法是:

Document doc = Jsoup.parse(html); 
String value = doc.select("#list > option:contains(Second value)").val();