Android - Derive the parent node of a child node using JSOUP

I have to change the html code of a web page before showing it on my Android App. This is my situation:

<html>
    <div class="something">
         <a class="inner_something">
             <span class="title">Titolo1</span>
         </a>
    </div>

    <div class="something">
          <a class="inner_something">
             <span class="title">Titolo2</span>
         </a>
    </div>
</html>

I want to remove the div that contains within it the span that contains the text= Titolo2. How i can do it?

Answers


Yes, you can do it with Jsoup:

String html = "<html>\n"
            + "    <div class=\"something\">\n"
            + "         <a class=\"inner_something\">\n"
            + "             <span class=\"title\">Titolo1</span>\n"
            + "         </a>\n"
            + "    </div>\n"
            + "\n"
            + "    <div class=\"something\">\n"
            + "          <a class=\"inner_something\">\n"
            + "             <span class=\"title\">Titolo2</span>\n"
            + "         </a>\n"
            + "    </div>\n"
            + "</html>";

Document doc = Jsoup.parseBodyFragment(html);
doc.select("div:has(a:has(span:contains(Titolo2)))").first().remove();

System.out.println(doc);

To load the processed HTML Document into your WebView, do:

 myWebView.loadData(doc.toString(), "text/html", "UTF-8");

You can also tweak the selector (doc.select("div.something");) to select and remove exactly what you want.

In your case, it's a little tricky: you have to select based on the content, so use :contains(text).


To count the number of divs with a certain class, do something like this:

Elements divs = doc.select("div.someclass");
int count = divs.size();

Will give you the count of divs with class someclass.


Need Your Help