Replace HTML tags using jsoup

Hardik Lotiya picture Hardik Lotiya · Sep 18, 2012 · Viewed 15.6k times · Source

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

Answer

ollo picture ollo · Sep 18, 2012

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());