I want to make an XPath request in this file (excerpt outlined):
<?xml version="1.0" encoding="UTF-8"?> <ModelClass xmlns="http://xml.sap.com/2002/10/metamodel/webdynpro" xmlns:IDX="urn:sap.com:WebDynpro.ModelClass:2.0"> <ModelClass.Parent> <Core.Reference package="com.test.mypackage" name="ModelName" type="Model"/>
This is the code snippet I'm using:
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = domFactory.newDocumentBuilder(); Document document = builder.parse(new File(testFile)); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); xpath.setNamespaceContext( new NamespaceContext() { public String getNamespaceURI(String prefix) { ... String result = xpath.evaluate(xpathQueryString, document); System.out.println(result);
The problem I'm encountering is that when the default namespace is referenced in an XPath request, the getNamespaceURI method is not called to fix it. This query, for example, does not retrieve anything:
//xmlns:ModelClass.Parent/xmlns:Core.Reference[@type=\"Model\"]/@package
Now I tried to βtrickβ the parser by replacing xmlns false prefix d and then typing the getNamespaceURI method getNamespaceURI (to return http://xml.sap.com/2002/10/metamodel/webdynpro when d is encountered). In this case, getNamespaceURI is getNamespaceURI , but the result of evaluating an XPath expression is always an empty string.
If I struck out the namespaces from the file and from the XPath query expression, I can get the desired line (com.test.mypackage).
Is there a way to work with the default namespace correctly?
java xml namespaces xpath xml-namespaces
Pietro M. May 23 '12 at 12:59 a.m. 2012-05-23 12:59
source share