当前位置: 代码迷 >> HTML/CSS >> nekohtml+xpath范例,及注意事项
  详细解决方案

nekohtml+xpath范例,及注意事项

热度:489   发布时间:2012-08-25 10:06:20.0
nekohtml+xpath实例,及注意事项

最近做项目用到了nekohtml+xpath

nekohtml将HTML文档解析为标准的DOM,再用XPath从DOM中抽取想要的结点。

nekohtml比起htmlparser还真是简单,但是简单就意味着不透明,出了错就不知是什么引起的,这一点真让人受不了。

下面先说说nekohtml+xpath的使用注意事项:

1.nekohtml会自动将html的标签转化为大写,因此写XPath时要用大写

//div 错误

//DIV 正确

2.用XPath处理时标签前要加命名空间,否则找不到结点,这里就要用到NamespaceContext这个类

?

class MyNamespaceContext implements NamespaceContext {
    private String ns;

    public MyNamespaceContext(String ns) {
        this.ns = ns;
    }

    public String getNamespaceURI(String prefix) {
        // TODO Auto-generated method stub
        if (prefix == null) {
            throw new NullPointerException("Null prefix");
        } else if (prefix.equals("pre")) {
            return this.ns;
        } else if (prefix.equals("xml")) {
            return XMLConstants.XML_NS_URI;
        }
        return XMLConstants.XML_NS_URI;
    }

    @Override
    public String getPrefix(String namespaceURI) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Iterator getPrefixes(String namespaceURI) {
        // TODO Auto-generated method stub
        return null;
    }
}

?

实例化XPath,并设置命名空间

?

XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        xpath.setNamespaceContext(new MyNamespaceContext("http://www.w3.org/1999/xhtml"));
        XPathExpression expr = xpath.compile("//pre:TITLE");
?

?

?

最后推介一个firefox的XPath插件--XPath checker

附近上源文件

?