2

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

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

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

  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 实现来强制执行此验证?

4

1 回答 1

1

尝试在您的实例上设置a :NamespaceContextXPath

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;
  }
}
于 2011-06-09T21:25:38.200 回答