使用jsoup解析XML——防止jsoup“清理"<链接>标签

2022-01-10 00:00:00 xml-parsing java jsoup link-tag

在大多数情况下,我使用 jsoup 解析 XML 没有问题.但是,如果XML文档中有<link>标签,jsoup会将<link>这里的一些文本</link>改为<link/>这里有一些文字.这使得无法使用 CSS 选择器提取 <link> 标记内的文本.

In most case, I have no problem with using jsoup to parse XML. However, if there are <link> tags in the XML document, jsoup will change <link>some text here</link> to <link />some text here. This makes it impossible to extract text inside the <link> tag using CSS selector.

那么如何防止jsoup清理"<link>标签呢?

So how to prevent jsoup from "cleaning" <link> tags?

推荐答案

在jsoup 1.6.2 我添加了一个 XML 解析器模式,它按原样解析输入,而不应用 HTML5 解析规则(元素内容、文档结构等).此模式会将文本保留在 <link> 标记中,并允许多个标记,等等.

In jsoup 1.6.2 I have added an XML parser mode, which parses the input as-is, without applying the HTML5 parse rules (contents of element, document structure, etc). This mode will keep text in a <link> tag, and allow multiples of it, etc.

这是一个例子:

String xml = "<link>One</link><link>Two</link>";
Document xmlDoc = Jsoup.parse(xml, "", Parser.xmlParser());

Elements links = xmlDoc.select("link");
System.out.println("Link text 1: " + links.get(0).text());
System.out.println("Link text 2: " + links.get(1).text());

返回:

Link text 1: One
Link text 2: Two

相关文章