I am having an Image tag as String. I need to parse the tag and add class and height and width for the tag. For this, I have used the below JSOUP code.
String imgTag = "<img class=\"fit-picture\" src=\"/Downloads/grapefruit-slice-332-332.jpg\" alt=\"Grapefruit slice atop a pile of other slices\">";
Document doc = Jsoup.parse(imgTag);
Elements img = doc.select("img");
for (Element image:img) {
image.addClass("abc");
String styleStr = image.attr("style");
boolean setSize = true;
if(styleStr != null && !styleStr.isEmpty() && (styleStr.contains("width") || styleStr.contains("height"))){
setSize = false;
}
if(setSize) {
String w = image.attr("width");
String h = image.attr("height");
if(w == null || w.isEmpty()) {
image.attr("width",width+"");
}
if(h == null || h.isEmpty() ) {
image.attr("height",height+"");
}
}
}
String imgrep = doc.body().html();
Output:
<img class="fit-picture abc" src="/Downloads/grapefruit-slice-332-332.jpg" alt="Grapefruit slice atop a pile of other slices" width="332" height="332">
In the above code, is it possible to achieve output without creating a JSOUP document? Like standalone Tag or Element object to achieve the same
Thanks in advance.