gpt4 book ai didi

java - 如何使用 Java 解析 HTML 标签中的数据

转载 作者:行者123 更新时间:2023-12-02 11:51:41 24 4
gpt4 key购买 nike

我正在从一个网站获取一个类似于 <HTML CODE HERE>Text I want to get 的字符串。并删除括号及其中的文本,但是,我的最终结果始终为空。

我正在尝试的是,

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();
}

最佳答案

看看 BufferedReader 的 Java API,即 readline:

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

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());

关于java - 如何使用 Java 解析 HTML 标签中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47839873/

24 4 0