kittu88 kittu88 - 4 months ago 15
Android Question

Add a new html tag to an html string in android

I have a string obtained from an EditText. The string contains html tags.

Spannable s = mainEditText.getText();
String webText = Html.toHtml(s);


The contents of the string is :

<p dir="ltr">test</p>
<p dir="ltr"><img src="http://files.parsetfss.com/bcff7108-cbce-4ab8-b5d1-1f82827e6519/tfss-0de7a730-3fa9-4a1e-9f82-d34e4f6e2d31-file" /><br /></p>
<p dir="ltr"><a href="22.572646,88.363895"><img src="http://maps.google.com/maps/api/staticmap?center=22.572646,88.363895&zoom=15&size=960x540&sensor=false&markers=color:blue%7Clabel:!%7C22.572646,88.363895" /></a><br /> </p>


Now, what I want to do is, wherever there is an img src tag, I want to precede it with a center tag.

What should I do to get the following output?

<p dir="ltr">test</p>
<p dir="ltr"><center><img src="http://files.parsetfss.com/bcff7108-cbce-4ab8-b5d1-1f82827e6519/tfss-0de7a730-3fa9-4a1e-9f82-d34e4f6e2d31-file" /></center><br /></p>
<p dir="ltr"><a href="22.572646,88.363895"><center><img src="http://maps.google.com/maps/api/staticmap?center=22.572646,88.363895&zoom=15&size=960x540&sensor=false&markers=color:blue%7Clabel:!%7C22.572646,88.363895" /></center></a><br /> </p>


Can a regex solve the issue or should it be done in a different way?

Can JSOUP help in any way? Is there any other type of HTML parser which can do the job?

Answer

I implemented the JSOUP solution suggested by mourphy. But, I had edited the method a little and it did the miracle for me. The new method is:

public String wrapImgWithCenter(String html){
     Document doc = Jsoup.parse(html);
        doc.select("img").wrap("<center></center>");
        return doc.html();
}

Thanks mourphy and vks for your help!