2009-11-05 48 views
0
一個HTMLEditorKit

我的HTML包含以下形式的標記的HTML文件:查詢的問題在Java中使用

<div class="author"><a href="/user/1" title="View user profile.">Apple</a> - October 22, 2009 - 01:07</div> 

我想提取的日期「2009年10月22日 - 01:07」在這個例子中,從每個標籤

我實現javax.swing.text.html.HTMLEditorKit.ParserCallback如下:

class HTMLParseListerInner extends HTMLEditorKit.ParserCallback { 
    private ArrayList<String> foundDates = new ArrayList<String>(); 
    private boolean isDivLink = false; 

    public void handleText(char[] data, int pos) { 
     if(isDivLink) 
      foundDates.add(new String(data)); // Extracts "Apple" instead of the date. 
    } 

    public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) {  
     String divValue = (String)a.getAttribute(HTML.Attribute.CLASS); 
     if (t.toString() == "div" && divValue != null && divValue.equals("author")) 
      isDivLink = true; 
    } 
} 

然而,上述分析程序返回「蘋果」,這是一個超鏈接裏的標籤內。我如何修復解析器來提取日期?

回答

0

覆蓋handleEndTag並檢查"a"

但是,這個HTML解析器是從90年代初開始的,這些方法沒有很好地指定。

+0

雖然我想到它,但在String中使用'=='通常不是個好主意。 – 2009-11-05 02:49:35

+0

我在Java中搜索了html解析器,這看起來很流行。如果你知道任何其他易於使用的解析器,我會很感激,如果你可以介紹他們。 – reprogrammer 2009-11-05 03:11:14

0
import java.io.*; 
import java.util.*; 
import javax.swing.text.*; 
import javax.swing.text.html.*; 
import javax.swing.text.html.parser.*; 

public class ParserCallbackDiv extends HTMLEditorKit.ParserCallback 
{ 
    private boolean isDivLink = false; 
    private String divText; 

    public void handleEndTag(HTML.Tag tag, int pos) 
    { 
     if (tag.equals(HTML.Tag.DIV)) 
     { 
      System.out.println(divText); 
      isDivLink = false; 
     } 
    } 

    public void handleStartTag(HTML.Tag tag, MutableAttributeSet a, int pos) 
    { 
     if (tag.equals(HTML.Tag.DIV)) 
     { 
      String divValue = (String)a.getAttribute(HTML.Attribute.CLASS); 

      if ("author".equals(divValue)) 
       isDivLink = true; 
     } 
    } 

    public void handleText(char[] data, int pos) 
    { 
     divText = new String(data); 
    } 

    public static void main(String[] args) 
    throws IOException 
    { 
     String file = "<div class=\"author\"><a href=\"/user/1\"" + 
      "title=\"View user profile.\">Apple</a> - October 22, 2009 - 01:07</div>"; 
     StringReader reader = new StringReader(file); 

     ParserCallbackDiv parser = new ParserCallbackDiv(); 

     try 
     { 
      new ParserDelegator().parse(reader, parser, true); 
     } 
     catch (IOException e) 
     { 
      System.out.println(e); 
     } 
    } 
}