避免使用 Saxon XPath 和 XHTML 使用名称空间前缀

Nei*_*gan 1 xhtml xpath namespaces saxon jaxp

使用 Saxon HE 9.6 作为 JAXP 实现

有一个带有 XHTML 命名空间的 HTML 文档

//*:title返回预期值,但//title不返回

我真的很想只使用//title. 如何才能做到这一点?

或者,我可以从已经构建的文档中删除命名空间吗?

Mar*_*nen 5

请参阅https://saxonica.plan.io/boards/3/topics/1649,您可以将XPath您从 Saxon XPathFactory 实现创建的 JAXP对象转换为 a net.sf.saxon.xpath.XPathEvaluator,然后为 XPath 评估设置默认的 XPath 命名空间,例如

((XPathEvaluator)xpath).getStaticContext().setDefaultElementNamespace("http://www.w3.org/1999/xhtml");
Run Code Online (Sandbox Code Playgroud)

然后路径//title将选择titleXHTML 名称空间中的元素。我测试了它在样本中的工作

    XPathFactory xpathFactory = new XPathFactoryImpl();
    XPath xpath = xpathFactory.newXPath();
    ((XPathEvaluator)xpath).getStaticContext().setDefaultElementNamespace("http://www.w3.org/1999/xhtml");


    String xhtmlSample = "<html xmlns='http://www.w3.org/1999/xhtml'><head><title>This is a test</title></head><body><h1>Test</h1></body></html>";
    InputSource source = new InputSource(new StringReader(xhtmlSample));

    System.out.println("Found: " + xpath.evaluate("//title", source));
Run Code Online (Sandbox Code Playgroud)