In looking over documentation on XPath queries it seemed easy enough to be able to pull out values from XML, but try as I might I kept getting no results back. Even searching on the root element “/elementName” didn’t return any results. Of course, as with all things Java there’s a trick and that trick is to call setNamespaceAware(). Here’s a quick and dirty example…
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(false); // NEVER FORGET THIS
DocumentBuilder builder = domFactory.newDocumentBuilder();
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("/items/item[@id='2']");
return (NodeList)expr.evaluate(domDocument, XPathConstants.NODESET);
Please remember to subscribe to the newsletter to stay up to date!You or someone you know looking to buy or sell?
Disclaimer: Thoughts and opinions are my own, and do not reflect the views of any employer, family member, friend, or anyone else. Some links may be affiliate links, but I don't link to anything I don't use myself. You would think this should be self evident these days, but apparently not...