XPathFinder { public List<String> queryTexts(String query) { try { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile(query); NodeList result = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); int length = result.getLength(); List<String> ret = new ArrayList<String>(length); for (int i = 0; i < length; i++) { Node item = result.item(i); String text = item.getNodeValue(); if (text == null && item.getChildNodes().getLength() > 0) { text = item.getFirstChild().getNodeValue(); } ret.add(text); } return ret; } catch (XPathExpressionException e) { throw new RuntimeException(e); } }  Document getDoc(); void setDoc(Document doc); void config(WebResponse response); NodeList query(String query); List<String> queryTexts(String query); List<Long> queryLongs(String query);  }
@Test public void testQueryTexts() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); ByteArrayInputStream in = new ByteArrayInputStream( "<a><b>2</b><b>4</b></a>".getBytes()); Document doc = builder.parse(in); XPathFinder finder = new XPathFinder(); finder.setDoc(doc); List<String> ret = finder.queryTexts(" assertEquals("2", ret.get(0)); assertEquals("4", ret.get(1)); assertEquals(2, ret.size()); }