如何在Android Java中将HTML转换为String?

问题描述 投票:0回答:2

我有这样的HTML格式:

"<div class=\"separator\" style=\"clear: both; text-align: center;\">\n
    <a href=\"https://i.pinimg.com/564x/c1/8e/21/c18e214e1dbd100a51d3256d080548cb.jpg\" 
        imageanchor=\"1\" style=\"margin-left: 1em; margin-right: 1em;\"><img border=\"0\" 
        data-original-height=\"800\" data-original-width=\"552\" 
        src=\"https://i.pinimg.com/564x/c1/8e/21/c18e214e1dbd100a51d3256d080548cb.jpg\" />
    </a>
</div>\n<br />"

如何从上述HTML https://i.pinimg.com/564x/c1/8e/21/c18e214e1dbd100a51d3256d080548cb.jpg获取src并转换为String?我想显示来自URL的图像,然后放入Glide ImageView。

java android
2个回答
0
投票

遍历html并搜索单词“ src”的首次出现。然后移至第一个“”,并将每个字符添加到数组/列表中,直到字符再次等于“”。

编辑:除了遍历整个事情,您还可以使用indexOf()获取src发生的位置,并如上所述从该位置进行迭代。


0
投票

HTML不是常规语言,因此无法使用正则表达式进行解析。但是有一个特殊的工具,我更喜欢Jsoup库。所以,这是代码段

build.gradle

dependencies {
//other dependencies
implementation "org.jsoup:jsoup:1.13.1" }

链接提取

  val text = "<div class=\"separator\" style=\"clear: both; text-align: center;\">" +
"<a href=\"https://i.pinimg.com/564x/c1/8e/21/c18e214e1dbd100a51d3256d080548cb.jpg\""+
"imageanchor=\"1\" style=\"margin-left: 1em; margin-right: 1em;\"><img border=\"0\""+
"data-original-height=\"800\" data-original-width=\"552\""+
"src=\"https://i.pinimg.com/564x/c1/8e/21/c18e214e1dbd100a51d3256d080548cb.jpg\" />"+
"</a>"+
"</div>\n<br />"
val doc = Jsoup.parse(text)
val link = doc.select(".separator a").attr("href").toString()
print(link)
© www.soinside.com 2019 - 2024. All rights reserved.