我有一个包含html代码的字符串,我只想从中提取某些元素。
我一直在寻找谷歌和堆栈溢出一段时间,似乎大多数建议的解决方案是使用Android XmlPullParser或JSoup。
这些方法中的哪一种最适合在android中解析hmtl,为什么?
JSOUP将是显而易见的选择,因为您可以轻松地识别HTML元素,并从中创建对象。最后,您可以执行所需的操作,将文档转换为字符串,最后在视图中进行设置。
下面是一个代码片段,我需要在其中删除网页的页眉和页脚,然后在视图中显示它。
if(document!=null) {
if (document.getElementById("header").getElementById("site-head") != null) {
document.getElementById("header").getElementById("site-head").remove();
}
if (document.getElementById("footer") != null) {
document.getElementById("footer").remove();
} if (document.getElementsByClass("fs-footer-newsletter") != null) {
document.getElementsByClass("fs-footer-newsletter").remove();
}
String modifiedDocument = document.toString();
modifiedDocument = modifiedDocument.replace("<html lang=\"en-US\" prefix=\"og: http://ogp.me/ns#\" class=\"no-js\">","<html lang=\"en-US\" prefix=\"og: http://ogp.me/ns#\" class=\"no-js\" style=\"margin-top:0 !important;\">");
modifiedDocument = modifiedDocument.replace("<header id=\"header\">","<header id=\"header\" style=\"margin-top:-16px;\">");
modifiedDocument = modifiedDocument.replace("<ul class=\"main-filters\">","<ul class=\"main-filters\" style=\"top:0;\">");
Document d = Jsoup.parse(modifiedDocument);
WebSettings ws = getItemWebview.getSettings();
ws.setJavaScriptEnabled(true);
Log.i("modifiedDocument",document.toString());
if(isURLForShop) {
loadingImg.setVisibility(View.GONE);
getItemWebview.loadDataWithBaseURL(storeUrl, d.toString(), "text/html", "utf-8", "");
}else{
loadingImg.setVisibility(View.GONE);
getItemWebview.loadDataWithBaseURL(restyleDenimURL, d.toString(), "text/html", "utf-8", "");
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句