I’m currently having an issue with my xpath expressions in java.
I’m trying to get a list of shopNames!
I got the following XML;
<?xml version="1.0" encoding="UTF-8"?>
<w:shops xmlns:w="namespace">
<w:shop>
<w:shopID>1</w:shopID>
<w:shopName>ShopName</w:shopName>
<w:shopURL>ShopUrl</w:shopURL>
</w:shop>
<w:shop>
<w:shopID>2</w:shopID>
<w:shopName>ShopNames</w:shopName>
<w:shopURL>ShopUrl</w:shopURL>
</w:shop>
</w:shops>
And I’m feeding this in a Document to a function alike this:
List<String> getShops(Document d)
throws Exception
{
List<String> shopnames = new ArrayList<String>();
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("/descendant::w:shop/descendant::w:shopName");
NodeList nodes = (NodeList) expr.evaluate(d, XPathConstants.NODESET);
for(int x=0; x<nodes.getLength(); x++)
{
shopnames.add("" + nodes.item(x).getNodeValue());
}
return shopnames;
}
However the issue is that it simply returns an empty list, I’m suspecting it to be my xpath expression, but I’m not sure about it.
Anyone see the issue here?
The root Element is not
shopbutshops. I think, you have to compile this expression:You may have to set a namespace context:
and parse so that the document is aware of namespaces