I try to use XPath with namespaces, but I do not get it going the way I would expect it.
import org.springframework.util.xml.*;
import javax.xml.namespace.*;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
public String foo () throws Exception
{
String xml = "<aaa:test xmlns:aaa=\"http://aaa\">123</aaa:test>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance ();
DocumentBuilder db = dbf.newDocumentBuilder ();
Document doc = db.parse (new ByteArrayInputStream (xml.getBytes())); //new ByteArrayInputStream (bodies.get (0)));
XPath xp = XPathFactory.newInstance ().newXPath ();
SimpleNamespaceContext snc = new SimpleNamespaceContext ();
snc.bindNamespaceUri ("aaa", "http://aaa");
xp.setNamespaceContext (snc);
String str1 = (String) xp.compile ("/test").evaluate (doc, XPathConstants.STRING);
String str2 = (String) xp.compile ("/aaa:test").evaluate (doc, XPathConstants.STRING);
System.out.println ("str1="+str1 + " str2="+str2);
// output: str1=123 str2=
xp = XPathFactory.newInstance ().newXPath ();
xp.setNamespaceContext(new NamespaceContext()
{
public String getNamespaceURI(String arg0)
{
if ("aaa".equals(arg0))
{
return "http://aaa";
}
return null;
}
public String getPrefix(String arg0) {
return null;
}
public Iterator<String> getPrefixes(String arg0) {
return null;
}
});
str1 = (String) xp.compile ("/test").evaluate (doc, XPathConstants.STRING);
str2 = (String) xp.compile ("/aaa:test").evaluate (doc, XPathConstants.STRING);
System.out.println ("str1="+str1 + " str2="+str2);
// output: str1=123 str2=
}
I would - at least - expect str2 to be equal to str1. Or better str2 with the value 123 and str1 with nothing - if namespaces are in use.
But what I get is str1 with the value and str2 with nothing.
I expect to use the namespace in the XPath query if one is in use. but it does not get me the value.
As you can see, I tried to define the namespace in two different ways, but none seems to be OK.