如何在Android中替换<img/>标记的src属性

时间:2013-07-18 05:44:31

标签: java android html html-parsing android-webview

我的应用程序是基于客户端 - 服务器的应用程序,我必须在WebView中显示存储在SDcard中的图像。
问题是从服务器端存储的字符串就像:

"<html><img id=\"MathMLEq1\" style=\"vertical-align: middle;\" src=\"/SOCH/img.PNG\" alt=\"\"/></html>"

我想在src tag已定义的值之前添加一些字符,如下所示:

"<html><img id=\"MathMLEq1\" style=\"vertical-align: middle;\" src=\"file:///mnt/sdcard/SOCH/img.PNG\" alt=\"\"/></html>"

任何人都可以帮我解决这个问题吗??? 在此先感谢..

2 个答案:

答案 0 :(得分:3)

String inputString = "<html><img id=\"MathMLEq1\" style=\"vertical-align: middle;\" src=\"/SOCH/img.PNG\" alt=\"\"/></html>";
StringBuffer q= new StringBuffer(inputString);
String add = "file:///mnt/sdcard";
int separatedInd = inputString.indexOf("/SOCH"); //Get the index of occurrence of the folder name in input string, which I assume remains same
q = q.insert(separatedInd ,add); //Insert your String at that index( before start of /SOCH)
String result = q.toString();  // Contains the new final string which you require

更新代码:

当您评论在同一个字符串中可能出现多个<img>标记时,以下是更新代码以替换所有所需位置的字符串:

ArrayList<Integer> arrayList = new ArrayList<Integer>();
// Assuming three times here
String inputString = "<html><img id=\"MathMLEq1\" style=\"vertical-align: middle;\" src=\"/SOCH/img.PNG\" alt=\"\"/></html> <html><img id=\"MathMLEq1\" style=\"vertical-align: middle;\" src=\"/SOCH/img.PNG\" alt=\"\"/></html> <html><img id=\"MathMLEq1\" style=\"vertical-align: middle;\" src=\"/SOCH/img.PNG\" alt=\"\"/></html>";
StringBuffer q= new StringBuffer(inputString);
String add = "file:///mnt/sdcard";
//Get all indexed of the occurrence of /SOCH string
for (int index = inputString.indexOf("/SOCH");
     index >= 0;
     index = inputString.indexOf("/SOCH", index + 1)){

    arrayList.add(index); //add the indexes to arrayList
}
int prev = 0;
for (int i = 0; i < arrayList.size(); i++){ // for all indexes
    q = q.insert(prev+ arrayList.get(i),add); //Insert the add string at position (index + (number of times 'add' string appears * length of 'add' string)  
    prev = (i+1)*add.length(); // calculate the next position where to insert the string

}
String result = q.toString(); //Gives the final output as desired.

希望这有帮助

答案 1 :(得分:0)

尝试使用JSOUP库。您可以使用它获取标记的属性,当您获得它时,您只需使用JAVA-s 替换方法。小心java字符串中的特殊字符(例如/)。您可以将其写入类似"\""的字符串中。阅读有关特殊字符的this article