Java IndexOf找不到合适的数据

时间:2013-03-12 14:50:52

标签: java parsing indexof

我有一个需要从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>

我的代码将被设置为它将在文档中搜索此字符串:     “&LT;风格”

然后搜索结束的carot:“&gt;”因为用户可能已为其HTML文件键入了以下任何组合:

<style type="text/css">

or

<style type = "text/css" >

or

<style type = 'text/css' >

or 

<style type='text/css'>

etc..

所以我的方法是找到“样式”标签以及截至结束的所有内容

然后找到结束样式标签:

</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;}

我在这里做错了什么。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

您从开始标记的末尾(结束括号>)获取子字符串并添加开始标记的长度(而不是endCarrot),从而移动开头的子串在您想要的位置之前。你想做什么

style = text.substring(openPos + endCarrot.length(), closePos).trim();

答案 1 :(得分:0)

当然......在我求助之后,我终于明白了。应更改以下代码

FROM:

style = text.substring(openPos + openTag.length(), closePos).trim();

TO:

style = text.substring(openPos + endCarrot.length(), closePos).trim();

对不起该帖子。并感谢您的建议

相关问题