Monday, October 31, 2011

Parsing XML and iterating it using XPath


How to parse XML from a string and iterate over a specific node name using Xpath

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

DocumentBuilder dBuilder = dbf.newDocumentBuilder();
String string = xmlBuffer.toString();
// not to parse a string you have to pass it in via stream
Document doc = dBuilder.parse(new InputSource(new ByteArrayInputStream(string.getBytes("utf-8"))));

XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
// match all nodes where the tag name is column and get the text content.
XPathExpression expr = xpath.compile("//column/text()");

Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
    logger.info(" "+nodes.item(i).getNodeValue());
}