2009-10-19 53 views
1

我需要轉換一些HTML文本嵌套標籤來裝飾「匹配」與CSS屬性來突出顯示它(如火狐搜索)。 我不能只是做一個簡單的替換(想想如果用戶搜索「img」例如),所以我試圖在正文文本(而不是標籤屬性)中進行替換。Swing Parser的handleText爲什麼不處理嵌套標籤?

我有一個非常簡單的HTML解析器,我覺得應該這樣做:

final Pattern pat = Pattern.compile(srch, Pattern.CASE_INSENSITIVE); 
Matcher m = pat.matcher(output); 
if (m.find()) { 
    final StringBuffer ret = new StringBuffer(output.length()+100); 
    lastPos=0; 
    try { 
     new ParserDelegator().parse(new StringReader(output.toString()), 
     new HTMLEditorKit.ParserCallback() { 
      public void handleText(char[] data, int pos) { 
       ret.append(output.subSequence(lastPos, pos)); 
       Matcher m = pat.matcher(new String(data)); 
       ret.append(m.replaceAll("<span class=\"search\">$0</span>")); 
       lastPos=pos+data.length; 
      } 
     }, false); 
     ret.append(output.subSequence(lastPos, output.length())); 
     return ret; 
    } catch (Exception e) { 
return output; 
    } 
} 
return output; 

我的問題是,當我調試這一點,handleText獲取調用與包括標籤的文字!這就像它只是深入一層。有人知道爲什麼是否有一些簡單的事情我需要做HTMLParser(沒有用太多)來啓用嵌套標籤的'正確'行爲?

PS - 我想出了自己 - 見下面的答案。簡而言之,如果您將HTML傳遞給HTML,而不是預先轉義的HTML,那麼它可以正常工作。衛生署!希望這可以幫助別人。

<span>example with <a href="#">nested</a> <p>more nesting</p> 
</span> <!-- all this gets thrown together --> 
+0

這似乎是c與'handleText'的API文檔一致... – 2009-10-19 15:22:49

回答

0

似乎在XP上使用JDK6對我很好。我用頭部和身體標籤包裝了您的示例HTML。我有三行輸出:

一)例如與 二)嵌套 C)更嵌套

這是我使用的代碼:

import java.io.*; 
import java.net.*; 
import javax.swing.text.html.parser.*; 
import javax.swing.text.html.*; 

public class ParserCallbackText extends HTMLEditorKit.ParserCallback 
{ 
    public void handleText(char[] data, int pos) 
    { 
     System.out.println(data); 
    } 

    public static void main(String[] args) 
     throws Exception 
    { 
     Reader reader = getReader(args[0]); 
     ParserCallbackText parser = new ParserCallbackText(); 
     new ParserDelegator().parse(reader, parser, true); 
    } 

    static Reader getReader(String uri) 
     throws IOException 
    { 
     // Retrieve from Internet. 
     if (uri.startsWith("http:")) 
     { 
      URLConnection conn = new URL(uri).openConnection(); 
      return new InputStreamReader(conn.getInputStream()); 
     } 
     // Retrieve from file. 
     else 
     { 
      return new FileReader(uri); 
     } 
    } 
} 
+0

感謝camickr不厭其煩地幫助驗證。對不起,我沒有提供更好的測試用例 - 這有助於我發現問題,因爲我試圖通過測試代碼運行我的示例。 - 吉姆P – 2009-10-21 20:42:51

0

對不起,誤導性的問題 - 我發現我的問題,並沒有包括在我的描述 - 我的輸入字符串已被預處理,所以我在看文本,如

<span>example with &lt;a href="#"&gt; nested &gt;/a&lt; &gt;p&lt;more nesting&gt;/p&lt; 
</span> <!-- well of course it all gets thrown together -->