我有一个需要从HTML页面解析HTML元素的java应用程序。我的简单HTML测试设置如下:
<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
div {width:100%;height:100px;background-color:blue;}
</style>
</head>
<body>
<div></div>
</body>
</html>
我的代码将设置为它将搜索文档中的这个字符串:"& # 60;风格"
然后搜索结束的胡萝卜:">"因为用户可能已经为他们的HTML文件输入了任何这些组合:
<style type="text/css">
or
<style type = "text/css" >
or
<style type = 'text/css' >
or
<style type='text/css'>
etc..
所以我的方法是找到"style"标签和所有的东西直到它的结束
然后找到结束样式标签:
</style>
然后抓取这两个实体之间的所有内容
以下是我的文件和它们的代码:
************strings.xml************
String txt_style_opentag = "<style"
String txt_end_carrot = ">"
String txt_style_closetag = "</style>"
***********************************
************Parser.java************
public static String getStyle(Context context, String text) {
String style = "";
String openTag = context.getString(R.string.txt_style_opentag);
String closeTag = context.getString(R.string.txt_style_closetag);
String endCarrot = context.getString(R.string.txt_end_carrot);
int openPos1 = text.indexOf(openTag);
int openPos = text.indexOf(endCarrot, openPos1);
int closePos = text.indexOf(closeTag, openPos1);
if (openPos != -1 && closePos != -1)
style = text.substring(openPos + openTag.length(), closePos).trim();
if (style != null && style.length() > 0 && style.charAt(0) == 'n') // first n remove
style = style.substring(1, style.length());
if (style != null && style.length() > 0 && style.charAt(style.length() - 1) == 'n') // last n remove
style = style.substring(0, style.length() - 1);
return style;
}
********************************************************
我的结果很接近,但不正确。结果如下:
{width:100%;height:100px;background-color:blue;}
如果你注意到,它缺少"div"部分。它应该看起来像这样:
div {width:100%;height:100px;background-color:blue;}
我做错了什么?有人能帮忙吗?
您正在从开始标记的末尾(结束括号>
)获取子字符串,并添加开始标记的长度(而不是endCarrot
),从而将子字符串的开始移动到您想要的位置之前。你想做
style = text.substring(openPos + endCarrot.length(), closePos).trim();
当然…在我寻求帮助之后,我终于弄明白了。下面的代码应该修改
来自:style = text.substring(openPos + openTag.length(), closePos).trim();
:
style = text.substring(openPos + endCarrot.length(), closePos).trim();
不好意思。谢谢你的推荐