tags:

views:

56

answers:

1

Hello,

     <div style="height:240px;">
 <br>test: example  <br>test1:example1 </div>

 Elements size = doc.select("div:contains(test:)");

how can i extract the value example and example1 from this html tag....using jsoup..

A: 

Since this HTML is not semantic enough for the final purpose you have (a <br> cannot have children and : is not HTML), you can't do much with a HTML parser like Jsoup. A HTML parser isn't intented to do the job of specific text extraction/tokenizing.

Best what you can do is to get the HTML content of the <div> using Jsoup and then extract that further using the usual java.lang.String or maybe java.util.Scanner methods.

Here's a kickoff example:

String html = "<div style=\"height:240px;\"><br>test: example<br>test1:example1</div>";
Document document = Jsoup.parse(html);
Element div = document.select("div[style=height:240px;]").first();

String[] parts = div.html().split("<br />"); // Jsoup transforms <br> to <br />.
for (String part : parts) {
    int colon = part.indexOf(':');
    if (colon > -1) {
        System.out.println(part.substring(colon + 1).trim());
    }
}

This results in

example
example1

If I was the HTML author, I would have used a definition list for this. E.g.

<dl id="mydl">
     <dt>test:</dt><dd>example</dd>
     <dt>test1:</dt><dd>example1</dd>
</dl>

This is more semantic and thus more easy parseable:

String html = "<dl id=\"mydl\"><dt>test:</dt><dd>example</dd><dt>test1:</dt><dd>example1</dd></dl>";
Document document = Jsoup.parse(html);
Elements dts = document.select("#mydl dd");
for (Element dt : dts) {
    System.out.println(dt.text());
}
BalusC