Java tutorial
//package com.java2s; /* Copyright (c) 2011 by crossmobile.org * * CrossMobile is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 2. * * CrossMobile is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CrossMobile; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { public static Node getNodeWithKey(Node parent, String key, String value) { HashSet<String> values = new HashSet<String>(); values.add(value); ArrayList<Node> nodes = getNodesWithKey(parent, key, values, false); if (nodes.size() < 1) return null; return nodes.get(0); } public static ArrayList<Node> getNodesWithKey(Node parent, String key, String value, boolean all_of_them) { HashSet<String> values = new HashSet<String>(); values.add(value); return getNodesWithKey(parent, key, values, all_of_them); } public static ArrayList<Node> getNodesWithKey(Node parent, String key, Set<String> values, boolean all_of_them) { ArrayList<Node> valid = new ArrayList<Node>(); NodeList children = parent.getChildNodes(); Node current; for (int i = 0; i < children.getLength(); i++) { current = children.item(i); NamedNodeMap attrs = current.getAttributes(); if (attrs != null) { Node keynode = attrs.getNamedItem(key); if (keynode != null) if (values == null || values.contains(keynode.getNodeValue())) { valid.add(current); if (!all_of_them) break; } } } return valid; } }