代码之家  ›  专栏  ›  技术社区  ›  reprogrammer

在Java中使用HTMLEditorKit查询HTML文件时出现问题

  •  1
  • reprogrammer  · 技术社区  · 16 年前

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

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

    然而,上述解析器返回“Apple”,它位于标签内的超链接内。如何修复解析器以提取日期?

    2 回复  |  直到 16 年前
        1
  •  0
  •   Tom Hawtin - tackline    16 年前

    handleEndTag 并检查 "a" ?

    然而,这个HTML解析器是90年代初的,这些方法没有很好地指定。

        2
  •  0
  •   camickr    16 年前
    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);
            }
        }
    }