我正在尝试将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:
答案 0 :(得分:2)
确实如此。考虑转移到XSLT 2.0 / XPath 2.0并使用Saxon的s9api接口。它看起来大致如下:Java XML API真是太痛苦了
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());