首页 > 解决方案 > 如何在 Parse Delegator 的帮助下忽略 html 文件的头部

问题描述

这里在输出中给出了 html 文件的所有内容,我只想打印 html 文件的正文内容需要忽略 xml 文件中的所有头部部分。使用解析器委托

  public static List<String> extractText(Reader reader) throws IOException {

    final ArrayList<String> list = new ArrayList<String>();
    ParserDelegator parserDelegator = new ParserDelegator();
    ParserCallback parserCallback = new ParserCallback() {
        public void handleText(final char[] data, final int pos) {
            list.add(new String(data));

        }

        public void handleStartTag(Tag tag, MutableAttributeSet attribute, int pos) {

        }

        public void handleEndTag(Tag t, final int pos) {

        }

        public void handleSimpleTag(Tag t, MutableAttributeSet a, final int pos) {
        }

        public void handleComment(final char[] data, final int pos) {
        }

        public void handleError(final java.lang.String errMsg, final int pos) {
        }
    };
    parserDelegator.parse(reader, parserCallback, true);
    return list;
}   
  public final static void main(String[] args) throws Exception{
            FileReader reader = new FileReader("test.xhtml");
            List<String> lines = bodyHtml.extractText(reader);
            for (String line : lines) {                 
                if(line != null && !line.trim().isEmpty())
                {
                    System.out.println(line.trim());
                }   
            }
          }

标签: javahtmlparsing

解决方案


推荐阅读