Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace HTML tags using jsoup

Tags:

java

jsoup

Here is my code

String html = "<font>fsdfs<font>dfsdf</font>dasdasd</font>";
Document doc = Jsoup.parse(html);
Elements elements = doc.select("font");
for(Element element : elements)
{
element.replaceWith(new Element(Tag.valueOf("span"),"").html(element.html()));
}


System.out.println(doc.html());

I want to replace font tag and put span tag. In this it will replace first font tag but not second tag

like image 615
Hardik Lotiya Avatar asked Sep 18 '12 10:09

Hardik Lotiya


People also ask

What is jsoup used for?

Jsoup is a Java html parser. It is a Java library that is used to parse html documents. Jsoup gives programming interface to concentrate and control information from URL or HTML documents. It utilizes DOM, CSS and Jquery-like systems for concentrating and controlling records.

Can jsoup parse JavaScript?

By calling the jsoup methods from the JavaScript and Python code, you can parse the webpage or HTML string and transform it into the DOM model, then traverse the DOM and find the required elements.

What is org jsoup in Java?

jsoup is a Java library for working with real-world HTML. It provides a very convenient API for fetching URLs and extracting and manipulating data, using the best of HTML5 DOM methods and CSS selectors.


1 Answers

You can replace the Tag like this too:

String html = "<font>fsdfs<font>dfsdf</font>dasdasd</font>";
Document doc = Jsoup.parse(html);
Elements elements = doc.select("font");


// rename all 'font'-tags to 'span'-tags, will also keep attributs etc.
elements.tagName("span");

System.out.println(doc.html());
like image 56
ollo Avatar answered Sep 21 '22 16:09

ollo