kittu88 kittu88 - 1 year ago 65
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="" /><br /></p>
<p dir="ltr"><a href="22.572646,88.363895"><img src=",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="" /></center><br /></p>
<p dir="ltr"><a href="22.572646,88.363895"><center><img src=",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 Source

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);"img").wrap("<center></center>");
        return doc.html();

Thanks mourphy and vks for your help!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download