[英]HTML annotation with JSOUP
我将需要根据网页的文本内容自动注释网页。 例如,我想注释有城市的html内容并添加一个跨度,例如:
barcelona --> <span class="city">barcelona</span>
问题是我根据文字内容而不是html知道城市的位置。 以前,我曾与JSoup合作,但是我找不到如何找到基于文本位置插入标签的位置。
这是达成目标的一种方法:
public static void main(String[] args) {
Document doc = Jsoup.parse("<p>Barcelona is a nice place to live !<br/>Other cities <b>too</b>!</p>");
dumpDocument("** BEFORE **", doc);
Matcher replacer = Pattern.compile("(?i)(barcelona)").matcher("");
for (Element elt : doc.body().select("*")) {
for (TextNode textNode : elt.textNodes()) {
String originalText = textNode.text();
if (replacer.reset(originalText).find()) {
String annotatedHtml = replacer.replaceAll("<span class=\"city\">$1</span>");
textNode.before(annotatedHtml);
textNode.remove();
}
}
}
dumpDocument("** AFTER **", doc);
}
private static void dumpDocument(String title, Document doc) {
System.out.println(title);
System.out.println(doc.html());
System.out.println();
}
OUTPUT
** BEFORE **
<html>
<head></head>
<body>
<p>Barcelona is a nice place to live !<br>Other cities <b>too</b>!</p>
</body>
</html>
** AFTER **
<html>
<head></head>
<body>
<p><span class="city">Barcelona</span> is a nice place to live !<br>Other cities <b>too</b>!</p>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.