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

expand within notebook does not work as expected

python python-2.7 tkinter

Here are attempts to get a Widget to stay in the center of the screen as the window re-sizes. By that I mean the normal behavior of a grid sticky='ew' with the frame packed to expand and fill='x'....

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.