Skip to content

Commit 5e0bf6d

Browse files
committed
XML: add method to get list of elements via xpath
It is nice to be able to painlessly write an xpath expression which you know will return a list of elements.
1 parent 6738b96 commit 5e0bf6d

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

src/main/java/org/scijava/util/XML.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
import java.io.PrintStream;
4040
import java.io.StringWriter;
4141
import java.net.URL;
42+
import java.util.ArrayList;
4243

4344
import javax.xml.parsers.DocumentBuilder;
4445
import javax.xml.parsers.DocumentBuilderFactory;
@@ -56,6 +57,7 @@
5657
import javax.xml.xpath.XPathFactory;
5758

5859
import org.w3c.dom.Document;
60+
import org.w3c.dom.Element;
5961
import org.w3c.dom.Node;
6062
import org.w3c.dom.NodeList;
6163
import org.xml.sax.SAXException;
@@ -184,6 +186,19 @@ public String cdata(final String expression) {
184186
return cdata(nodes.item(0));
185187
}
186188

189+
/** Obtains the elements identified by the given XPath expression. */
190+
public ArrayList<Element> elements(final String expression) {
191+
final NodeList nodes = xpath(expression);
192+
final ArrayList<Element> elements = new ArrayList<Element>();
193+
if (nodes != null) {
194+
for (int i=0; i<nodes.getLength(); i++) {
195+
final Node node = nodes.item(i);
196+
if (node instanceof Element) elements.add((Element) node);
197+
}
198+
}
199+
return elements;
200+
}
201+
187202
/** Obtains the nodes identified by the given XPath expression. */
188203
public NodeList xpath(final String expression) {
189204
final Object result;

0 commit comments

Comments
 (0)