JAXP:如何强制XPath验证名称空间前缀?

时间:2011-06-09 17:42:46

标签: java xml validation xpath jaxp

我依赖于默认的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实施强制执行此验证?

1 个答案:

答案 0 :(得分:1)

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;
  }
}