2015-12-06 57 views
1

我需要根據網頁的文本內容自動註釋網頁。比如我要標註那裏有城市的HTML內容,並添加一個跨度,如:帶JSOUP的HTML註釋

barcelona --> <span class="city">barcelona</span>

的問題是,我知道基於文本內容的城市的位置,而不是HTML。之前我曾與JSoup合作過,但我找不到如何根據文本位置找到插入標籤的位置。

+1

嗨,這將是很好,如果你還可以添加整個HTML內容與你的預期輸出。 –

回答

0

這裏是acheive你的目標的方式:

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

輸出

** 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>