jSoup - remove particular style attributes
java, jsoup
Solution
Try this:
Document doc = Jsoup.parse(html);
Elements e = doc.getElementsByTag("body");
Log.i("Span element: "+e.get(0).nodeName(), ""+e.get(0).nodeName());
e = e.get(0).getElementsByTag("span");
Attributes styleAtt = e.get(0).attributes();
Attribute a = styleAtt.asList().get(0);
if(a.getKey().equals("style")){
String[] items = a.getValue().trim().split(";");
String newValue = "";
for(String item: items){
if(item.contains("COLOR:")||item.contains("FONT-SIZE:")){
Log.i("Style Item: ", ""+item);
newValue = newValue.concat(item).concat(";");
}
}
a.setValue(newValue);
Log.i("New Atrrbute: ",""+newValue);
}
Log.i("FINAL HTML: ",""+e.outerHtml());
doc.html(e.outerHtml());
}
Output:
`08-17 18:28:07.692: I/FINAL HTML:(8148): <span style=" COLOR: #003572; FONT-SIZE: 9pt;">Dr. Who is <u>usually</u> available for consultations Mon - Thurs afternoons and Friday 9a- 12p at 555-1212. </span>`
Cheers,
Problem
Am I missing something? Is there a better way to do this? INPUT: ``` <span style="FONT-FAMILY: 'Lucida Sans','sans-serif'; COLOR: #003572; FONT-SIZE: 9pt; mso-fareast-font-family: Calibri; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA; mso-fareast-theme-font: minor-latin">Dr. Who is <u>usually</u> available for consultations Mon - Thurs afternoons and Friday 9a- 12p at 555-1212. </span> ``` DESIRED OUTPUT: <span style="COLOR: #003572; FONT-SIZE: 9pt;">Dr. Who is <u>usually</u> available for consultations Mon - Thurs afternoons and Friday 9a-12p at 555-1212. </span> MY CODE SO FAR: //cleans the HTML within the Week Long note before writing to the DB ``` Whitelist wl = new Whitelist(); wl = Whitelist.simpleText(); wl.addTags("br"); wl.addTags("p"); wl.addTags("span"); wl.addAttributes(":all","style"); Document doc = Jsoup.parse( "<html><head></head><body>"+ds.getWeeklongNote()+"</body></html>"); Elements e = doc.select("*"); for (Element el : e){ for (Attribute attr : el.attributes()){ if (attr.getKey().equals("span")){ String newValue = ""; String s = attr.getValue(); String[] values = s.split(";"); for (String value : values){ if (value.startsWith("COLOR")||value.startsWith("FONT-SIZE")){ newValue += attr.getKey()+"="+attr.getValue()+";"; } } attr.setValue(newValue); } } } doc.html(e.outerHtml()); ds.setWeekLongNote(Jsoup.clean(doc.body().outerHtml(), wl)); ```