TagSoup和XPath

时间:2011-07-21 21:46:14

标签: java xpath tag-soup

我正在尝试将TagSoup与XPath(JAXP)一起使用。我知道如何从TagSoup(或XMLReader)获取SAX解析器。但我没有找到如何创建将使用该SAX解析器的DocumentBuilder。我该怎么做?

谢谢。

编辑:很抱歉这么一般,但Java XML API真是太痛苦了。

EDIT2:

问题解决了:

public static void main(String[] args) throws XPathExpressionException, IOException,
        SAXNotRecognizedException, SAXNotSupportedException,
        TransformerFactoryConfigurationError, TransformerException {

    XPathFactory xpathFac = XPathFactory.newInstance();
    XPath xpath = xpathFac.newXPath();

    InputStream input = new FileInputStream("/tmp/g.html");

    XMLReader reader = new Parser();
    reader.setFeature(Parser.namespacesFeature, false);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();

    DOMResult result = new DOMResult();
    transformer.transform(new SAXSource(reader, new InputSource(input)), result);

    Node htmlNode = result.getNode();
    NodeList nodes = (NodeList) xpath.evaluate("//span", htmlNode, XPathConstants.NODESET);
    System.out.println(nodes.getLength());
}

EDIT3:

帮助我的链接:http://www.jezuk.co.uk/cgi-bin/view/jez?id=2643

1 个答案:

答案 0 :(得分:2)

  

Java XML API真是太痛苦了

确实如此。考虑转移到XSLT 2.0 / XPath 2.0并使用Saxon的s9api接口。它看起来大致如下:

Processor proc = new Processor();

InputStream input = new FileInputStream("/tmp/g.html");
XMLReader reader = new Parser();
reader.setFeature(Parser.namespacesFeature, false);
Source source = new SAXSource(parser, input);

DocumentBuilder builder = proc.newDocumentBuilder();
XdmNode input = builder.build(source);

XPathCompiler compiler = proc.newXPathCompiler();
XdmValue result = compiler.evaluate("//span", input);
System.out.println(result.size());