如何更改Android本地存储的某些页面的HTML代码中的href值?
private void changeHrefsToLocal(String pageName) throws IOException {
File input = new File(appContext.getFilesDir(), pageName);
Document savedDoc = Jsoup.parse(input, "UTF-8");
Elements links = savedDoc.select("a[href]");
String href;
for(Element link : links){
href = appContext.getFilesDir() + "/" + link.attr("abs:href").replace(INDEX_URL, "") + ".html";
link.attr("href", href);
}
}
日志:
11-23 18:40:33.837 10380-10397/com.pokropek.ernest.protectedofflinewebviewer E/testing: <a href="http://test.pl/kontakt">Kontakt</a>
11-23 18:40:33.837 10380-10397/com.pokropek.ernest.protectedofflinewebviewer E/testing: <a href="/data/data/com.pokropek.ernest.protectedofflinewebviewer/files/kontakt.html">Kontakt</a>
如果我在该方法运行之前和之后打印到日志的链接,则可能会有预期的更改,尽管本地.html文件中没有没有更改,这是主要问题。
答案 0 :(得分:0)
很简单,只需将编辑后的html文件保存回去。
这是示例代码
File input = new File(appContext.getFilesDir(), pageName);
Document savedDoc = null;
try {
savedDoc = Jsoup.parse(input, "UTF-8");
} catch (Exception e) {
Log.e("Error ", e.toString());
}
Elements links = savedDoc.select("a[href]");
for(Element link : links){
link.attr("href", "changed value");//change the value of href attribute here
}
//save the updated/edited html file
PrintWriter writer;
try {
writer = new PrintWriter(input,"UTF-8");
writer.write(savedDoc.html() ) ;
writer.flush();
writer.close();
} catch (Exception e) {
Log.e("Error ", e.toString());
}