MRalwasser
MRalwasser

Reputation: 15953

JAXP: How to force XPath to validate namespace prefixes?

I am relying on the default JAXP implementation and using the Oracle JRE. When evaluating a XPath which contains an unknown namespace prefix, it does not throw an (expected) exception.

When I run the same application on an IBM JRE, everything is fine and it throws the expected exception javax.xml.xpath.XPathExpressionException: org.apache.xpath.domapi.XPathStylesheetDOM3Exception: Prefix must resolve to a namespace

I am using the following code which tries to access an invalid 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);

Question:

How can I enforce this validation independently from the JAXP implementation?

Upvotes: 2

Views: 4257

Answers (1)

McDowell
McDowell

Reputation: 108879

Try setting a NamespaceContext on your XPath instance:

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

Upvotes: 1

Related Questions