Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jsoup accessing the HTML select tag

Tags:

java

html

jsoup

I'm new to jsoup and having a bit of trouble with html tag. I need to get value attribute of select list options based on a text they contain. For example:

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

Do you have an idea how I can tell jsoup to return the value "1" if it gets a "Second value" as a parameter for a search?

like image 453
Igor Sabo Avatar asked Dec 06 '22 12:12

Igor Sabo


1 Answers

Here's another solution:

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

Test:

Document doc = Jsoup.parse(html); // html is your listed html / xml
Strign result = searchAttribute(doc, "Second value") // result = 1
like image 200
ollo Avatar answered Dec 23 '22 17:12

ollo