Java XPath: Queries with default namespace xmlns

ghettomex

New Member
I want to do an XPath query on this file (excerpt shown):\[code\]<?xml version="1.0" encoding="UTF-8"?><!-- MetaDataAPI generated on: Friday, May 25, 2007 3:26:31 PM CEST --><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"/>\[/code\]This is a snippet of the code I'm using:\[code\]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);\[/code\]The problem I'm facing is that when the default namespace is referenced in an XPath query, the getNamespaceURI method is not called to resolve it.This query for example doesn't extract anything:\[code\]//xmlns:ModelClass.Parent/xmlns:Core.Reference[@type=\"Model\"]/@package\[/code\]Now I've tried "tricking" the parser by replacing \[code\]xmlns\[/code\] with a fake prefix \[code\]d\[/code\] and then writing the \[code\]getNamespaceURI\[/code\] method accordingly (so to return \[code\]http://xml.sap.com/2002/10/metamodel/webdynpro\[/code\] when \[code\]d\[/code\] is encountered). In this case, the \[code\]getNamespaceURI\[/code\] is called but the result of the XPath expression evaluation is always an empty string.If I strip out namespaces from the file and from the XPath query expression, I can get the string I wanted (com.test.mypackage).Is there a way to make things work properly with the default namespace?
 
Back
Top