使用 Jsoup 解析 HTML 以获取单个元素的文本

Parse HTML to get text for individual elements using Jsoup

我需要解析以下文本并为每个文本创建单独的对象。我尝试了几种方法,但它没有提供我需要的格式的结果。

正文是:

String text = "This is start of a text&nbsp;<a href=\"https://google.com/sample\">followed by a link&nbsp;sample</a>and ending with some text."

使用以下代码:

Document document = Jsoup.parse(text);
Elements elements = document.select("*");
for(Element e : elements){
System.out.println( e.tagName() + ": " + e.text());}

实际结果是

root: This is start of a text followed by a link sampleand ending with some text.
html: This is start of a text followed by a link sampleand ending with some text.
head: 
body: This is start of a text followed by a link sampleand ending with some text.
p: This is start of a text followed by a link sampleand ending with some text.
a: followed by a link sample

我需要获得以下结果,以便为每个文本创建一个自定义对象

body: This is start of a text&nbsp;
a:followed by a link&nbsp;sample
body:and ending with some text.

为避免返回所有子项的文本,请使用 e.ownText(),但在这种情况下这还不够,因为您希望单独使用 This is start of a textand ending with some text.,但 ownText() returns 它加入了:This is start of a text and ending with some text..
要获取分隔文本的列表,请使用 e.textNodes() 并且 body 的输出将是:

body: [
This is start of a text&nbsp;, and ending with some text.]
a: [followed by a link&nbsp;sample]

还有一个额外的好处是您可以保持原创 &nbsp;
此外,如果您不喜欢将多余的 html: []head: [] 添加到您的文档中,您应该使用 XML 解析器:

Document document = Jsoup.parse(text, "", Parser.xmlParser());

为了保持文本分离和 <a> 文本按顺序尝试递归迭代:document.childNodes(),然后对每个节点使用 childNodes()。您可以通过检查 if (node instanceof TextNode).

来识别文本节点