Java tutorial
//package com.java2s; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.util.ArrayList; import java.util.List; public class Main { /** * Return children of the {@code node} parameter with a matching {@code nodeName} & * {@code attributeName} that matches at least one of the passed-in {@code attributeValues}. * If {@code attributeValues} is empty, no nodes will match. To match names only, * pass null for both {@code attributeName} and {@code attributeValues}. * * @param node the root node to look beneath. * @param nodeName all child nodes will match this element. * @param attributeName all matching child nodes will have an attribute of this name. * @param attributeValues all matching child nodes' matching attribute will have a value that * matches one of these values. * @return child nodes that match all parameters */ static List<Node> getMatchingChildNodes(final Node node, final String nodeName, final String attributeName, final List<String> attributeValues) { if (node == null || nodeName == null) { return null; } final List<Node> nodes = new ArrayList<Node>(); final NodeList nodeList = node.getChildNodes(); for (int i = 0; i < nodeList.getLength(); ++i) { Node childNode = nodeList.item(i); if (childNode.getNodeName().equals(nodeName) && nodeMatchesAttributeFilter(childNode, attributeName, attributeValues)) { nodes.add(childNode); } } return nodes; } /** * Returns {@code true} iff the node has the attribute {@code attributeName} with a value that * matches one of {@code attributeValues}. */ static boolean nodeMatchesAttributeFilter(final Node node, final String attributeName, final List<String> attributeValues) { if (attributeName == null || attributeValues == null) { return true; } final NamedNodeMap attrMap = node.getAttributes(); if (attrMap != null) { Node attrNode = attrMap.getNamedItem(attributeName); if (attrNode != null && attributeValues.contains(attrNode.getNodeValue())) { return true; } } return false; } static String getNodeValue(final Node node) { if (node != null && node.getFirstChild() != null && node.getFirstChild().getNodeValue() != null) { return node.getFirstChild().getNodeValue().trim(); } return null; } }