XPath processing with namespaces does not work. Please review my code..
Dear all,
I am working on with the IMS Group's Enterprise XML standard (http://www.imsproject.org/enterprise/) and need to retrieve member information using XPath.
After significant fault finding, I have narrowed down the problem to the XML file containing multiple namespaces in the root element. I have checked out some forum postings here and on Google (programmer's best friend) for possible solutions... namely the implementation of the my own NamespaceContext object. I have implemented and yet I am still not able to retrieve the data I want.
Could someone advise where I am going wrong?
When I remove the namespaces from the root element I can find out the number of member elements in the XML (just for testing atm). I could write a regular expression to remove the namespaces from my XML, but that's just dodgy..
Here's a sample XML:
<enterprise xmlns="http://www.imsproject.org/xsd/imsep_rootv1p01" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:webct="http://www.webct.com/IMS">
<properties>...</properties>
<group>...</group>
<membership>
<member>...</member>
</membership>
</enterprise>
My implementation of the a NamespaceContext object:
public class IMSProjectNamespaceContext implements NamespaceContext {
public String getNamespaceURI(String prefix) {
if(prefix == null) throw new NullPointerException("Null prefix");
else if("xsi".equals(prefix)) return "http://www.w3.org/2001/XMLSchema-instance";
else if("webct".equals(prefix)) return "http://www.webct.com/IMS";
else if("xml".equals(prefix)) return XMLConstants.XML_NS_URI;
return XMLConstants.NULL_NS_URI;
}// end of overriding getNamespaceURI method
// This method is not necessary for XPath processing
public String getPrefix(String uri) {
throw new UnsupportedOperationException();
}// end of overriding getPrefix method
// This method is not necessary for XPath processing
public java.util.Iterator getPrefixes(String uri) {
throw new UnsupportedOperationException();
}// end of overriding getPrefixes method
}// end of IMSProjectNamespaceContext class
My method attempting to use XPath... but not successful (it should print out the number of member elements if XPath works correctly with my XML file, but only prints out 0 each time):
private void getSectionMembers(String dataXML) throws Exception {
try {
InputSource inputSource = new InputSource(new StringReader(dataXML));
XPath xPath = XPathFactory.newInstance().newXPath();
xPath.setNamespaceContext(new IMSProjectNamespaceContext());
XPathExpression xPathExpression = xPath.compile("/enterprise/membership/member");
NodeList nodes = (NodeList)xPathExpression.evaluate(inputSource, XPathConstants.NODESET);
System.out.println(nodes.getLength()); // Debugging
} catch(Exception ex) {
ex.printStackTrace();
throw new Exception("XPath Querying Failed.");
}
}// end of xPathQuery method

