Java examples for XML:XPath
Select Elements from parent element by XPath
// This program is free software; you can redistribute it and/or modify it //package com.java2s; import org.w3c.dom.*; import javax.xml.xpath.*; import java.util.*; public class Main { public static List<Element> SelectElements(Element parent, String expression) {//from w w w.j a v a2 s. co m List<Element> nodes = new ArrayList<Element>(); XPath xpath = getXPath(); try { XPathExpression xpathExpression = xpath.compile(expression); NodeList nodeList = (NodeList) xpathExpression.evaluate(parent, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { nodes.add((Element) (nodeList.item(i))); } } catch (Exception e) { throw new RuntimeException(e); } return nodes; } public static XPath getXPath() { return getXPathFactory().newXPath(); } public static XPathFactory getXPathFactory() { return XPathFactory.newInstance(); } }