我依靠默认的JAXP实现,并使用Oracle JRE。
评估包含未知名称空间前缀的XPath时,它不会引发(预期)异常。

当我在IBM JRE上运行相同的应用程序时,一切都很好,并且会引发预期的异常javax.xml.xpath.XPathExpressionException: org.apache.xpath.domapi.XPathStylesheetDOM3Exception: Prefix must resolve to a namespace

我正在使用以下代码尝试访问无效的命名空间unknownns

  DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
      .newInstance();

  documentBuilderFactory.setNamespaceAware(true);
  documentBuilderFactory.setValidating(true);
  documentBuilderFactory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);

  DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();

  Document doc = builder.parse(xmlFile_);

  XPath xpath = XPathFactory.newInstance().newXPath();
  NodeList nodeList = (NodeList) xpath.evaluate("path/to/node/unknowns:@bla", doc,
      XPathConstants.NODESET);


题:

如何独立于JAXP实施而强制执行此验证?

最佳答案

在您的NamespaceContext实例上尝试setting一个XPath

public final class NSValidator {
  private NSValidator() {
  }

  private static final NamespaceContext INSTANCE = new NamespaceContext() {
    @Override public String getNamespaceURI(String prefix) {
      return null;
    }

    @Override public String getPrefix(String namespaceURI) {
      return null;
    }

    @Override public Iterator<?> getPrefixes(String namespaceURI) {
      return Collections.emptyList()
          .iterator();
    }
  };

  public static NamespaceContext noNamespaces() {
    return INSTANCE;
  }
}

10-08 02:32