最近因为项目需要,研究了java html parser类库的应用。记录下使用要点:

主要的类说明:

1、Parser类

解析器主类,负责载入HTML代码并解析。

2、Node接口

用来表征在解析过程中使用的语法单元。示例如下段html代码:

----Tag node

text ----Text Node

文本和标签都是独立的node元素。text文本是标签span的child node

3、NodeFilter

标签过滤器接口,用来在parser或NodeList中过滤出需要的某一类node。

4、NodeList

数据结构,表示Node的集合

需要特别注意的地方:

Parser和NodeList都有一个名为extractAllNodesThatMatch(NodeFilter filter)的方法用来过滤出符合某个条件的node,但是其内部的实现机制不同。

Parser是在解析器的功能基础上使用Iteror实现。每次调用该方法后需要执行reset方法,否则会影响下一次调用的结果。

而NodeList是在内部的数组上进行循环判断,因此各次调用之间不会互相影响,效率也比Parser的高,土建使用。

代码示例:

实现getElementByID功能

public class NodeIDFilter implements NodeFilter {

private String id;

public NodeIDFilter(String id)

{

this.id=id;

}

public boolean accept(Node node) {

if(node instanceof Tag)

{

if(!((Tag)node).isEndTag())

{

String s=((Tag)node).getAttribute("id");

if(s!=null)

return s.equals(this.id);

}

}

return false;

// throw new UnsupportedOperationException("Not supported yet.");

}

}

public class MHTMLParser

{

....

protected Node getElementById(String id) throws ParserException

{

//this.myparser.reset();

if(this.mNodeList==null||this.mNodeList.size()==0) return null;

NodeIDFilter nodef = new NodeIDFilter(id);

NodeList nl = this.mNodeList.extractAllNodesThatMatch(nodef,true);

//

if (nl.size() != 0)

{

return nl.elementAt(0);

}

return null;

}

}

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐