public static Object xPathQuery(String expression, File file) { Document document; DocumentBuilderFactory dBF = DocumentBuilderFactory.newInstance(); Object result = null; try { DocumentBuilder builder = dBF.newDocumentBuilder(); document = builder.parse(file); XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expr = xpath.compile(expression); result = expr.evaluate(document, XPathConstants.NODESET); } catch (Exception e) { e.printStackTrace(); } return result; }
You can see that this method returns Object. This object can be cast to boolean, String or (more useful) NodeList. Be careful, this type depends of type of your XPath query. So for example to extract NodeList from XPath query that returns multiple nodes will look like this:
NodeList nodes = (NodeList) xPathQuery("//employees", new File("C:/some_xml")); int j = nodes.getLength(); for (int i = 0; i < j; i++) { System.out.println(nodes.item(i).getTextContent()); }
And that's it!
No comments:
Post a Comment