如何使用Java解析HTML标记中的数据

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

我从一个看起来像<HTML CODE HERE>Text I want to get的网站中取出一个字符串并删除其中的括号和文本,但是,我的最终结果始终为null。

我在想的是,

try {
        String desc = null;
        StringBuilder sb = new StringBuilder();
        BufferedReader r = new BufferedReader(new InputStreamReader(in));
        String line = null;
        boolean codeBlock;
        codeBlock = false;

        line = "<HTMLCODEHERE>Text I want to get";
        System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! STARTING DESC: " + line);

        while((line = r.readLine()) != null) {
            if((line = r.readLine()) == "<") {
                codeBlock = true;
            }
            if((line = r.readLine()) == ">") {
                codeBlock = false;
            }
            if(!codeBlock) {
                sb.append(line);
                desc = sb.toString();
            }
        }

        System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ENDING DESC: " + desc);
        holder.txtContent.setText(desc);
    } catch (IOException e) {
        e.printStackTrace();
    }
java string
1个回答
1
投票

看看BufferedReader的Java API,即readline:

读一行文字。一条线被认为是由换行符('\ n'),回车符('\ r')或回车符中的任何一个终止,后面紧跟换行符。

https://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine()

因此你的代码在这里:

if((line = r.readLine()) == "<") {
    codeBlock = true;
}
if((line = r.readLine()) == ">") {
    codeBlock = false;
}

永远不会是真的。这些电话也会让您远离目前的分析线。

如果我正确理解您的问题,您希望任何HTML标记之间的所有文本?您可以使用像jsoup这样的库,或者实现更简单的实现:

String parse = "<HTMLCODE>My favourite pasta is spaghetti, followed by ravioli</HTMLCODE>";

final char TAG_START = '<';
final char TAG_END = '>';

StringBuilder sb = new StringBuilder();

char[] parseChars = parse.toCharArray();

boolean inTag = true;
for (int i = 0; i< parseChars.length; i++) {
    if (parseChars[i] == TAG_START) {
        inTag = true;
        continue;
    }
    else if (parseChars[i] == TAG_END) {
        inTag = false;
        continue;
    }
    if (!inTag) {
        sb.append(parseChars[i]);
    }
}

System.out.println(sb.toString());
© www.soinside.com 2019 - 2024. All rights reserved.