Java tutorial
//package com.java2s; //License from project: Apache License import java.util.ArrayList; import java.util.List; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** * Returns all nodes at the bottom of path from node. * If element begins with '@', indicates an attribute, eg "@id" * The '#text' element indicates that the node has a single text child. * @param node Node to apply path to * @param path Path to apply * @return All nodes at bottom of path. List may be empty but not null. */ static public List<Node> extractPaths(Node node, String[] path) { List<Node> result = new ArrayList<Node>(); result.add(node); for (int i = 0; i < path.length; i++) { List<Node> children = new ArrayList<Node>(); for (int j = 0; j < result.size(); j++) children.addAll(extractNodes((Node) result.get(j), path[i])); result = children; } return result; } /** * Returns all nodes at the bottom of path from node. * If element begins with '@', indicates an attribute, eg "@id" * The '#text' element indicates that the node has a single text child. * @param node Node to apply path to * @param path Path to apply * @return All Nodes at bottom of path. List may be empty, but not null. */ static public List<Node> extractNodes(Node node, String path) { if (node == null) return new ArrayList<Node>(); List<Node> result = new ArrayList<Node>(); NodeList list = node.getChildNodes(); if (path.equals("#text")) result.add(node.getFirstChild()); else if (path.charAt(0) == '@') result.add(node.getAttributes().getNamedItem(path.substring(1))); else for (int j = 0; j < list.getLength(); j++) if (list.item(j).getNodeType() == Node.ELEMENT_NODE && list.item(j).getNodeName().equals(path)) result.add(list.item(j)); return result; } }