Replacing text inside tags using Jsoup

2019-07-28 01:42发布

<table width="100%" border="0" cellpadding="0" cellspacing="1" class="table_border" id="center_table">
<tbody>
<tr>
<td width="25%" class="heading_table_top">S. No.</td>
<td width="45%" class="heading_table_top">
Booking Status (Coach No , Berth No., Quota)
</td>
<td width="30%" class="heading_table_top">
* Current Status (Coach No , Berth No.)
</td>
</tr>
</tbody>
</table>

I scrap a webpage and store the response in a string.

I then parse it into jsoup doc

Document doc = Jsoup.parse(result);

Then i select the table using

Element table=doc.select("table[id=center_table]").first();

Now i need to replace the text in tag "Booking Status (Coach No , Berth No., Quota)" to "Booking Status" using jsoup.. Could anybody help ?

I tried

  table.children().text().replaceAll(RegEx to select the text?????, "Booking Status");

2条回答
Juvenile、少年°
2楼-- · 2019-07-28 01:57
Elements tablecells=doc.select("table tbody tr td");

will give you 3 cells. use a loop to get the each element with

Element e=Elements.get(int index);

Use the e.text() to get the String.

Compare or replace strings with String.equals() , String.contains(), String.replace()

查看更多
Viruses.
3楼-- · 2019-07-28 02:01
        Elements tds=doc.select("table[id=center_table] td");  // select the tds from your table
        for(Element td : tds) {  // loop through them
            if(td.text().contains("Booking Status")) {  // found the one you want
                td.text("Booking Status");          // Replace with your text
            }
        }

then you can use doc.toString() to get the text of the HTML back to save to disk, send to a webView or whatever else you want to do with it.

查看更多
登录 后发表回答