Java tutorial
//package com.java2s; /*L * Copyright RTI International * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/webgenome/LICENSE.txt for details. */ import java.util.Enumeration; import java.util.Properties; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** * Find element in XML document with given property * @param doc XML document * @param tagName Tag name * @param propName Property name * @param propValue Property value * @return Element or null if not found */ public static Element findElement(Document doc, String tagName, String propName, String propValue) { Properties props = new Properties(); props.put(propName, propValue); return findElement(doc, tagName, props); } /** * Find an element * @param doc XML document * @param tagName Tag name * @param props Properties corresponding to attributes in tag * @return Element or null if not found */ public static Element findElement(Document doc, String tagName, Properties props) { Element elmt = null; NodeList nlist = doc.getElementsByTagName(tagName); for (int i = 0; i < nlist.getLength() && elmt == null; i++) { Node node = nlist.item(i); if (node instanceof Element) { Element temp = (Element) node; boolean matches = true; for (Enumeration en = props.keys(); en.hasMoreElements() && matches;) { String name = (String) en.nextElement(); String value = props.getProperty(name); String attValue = temp.getAttribute(name); if (attValue == null) matches = false; else if (!value.equals(attValue)) matches = false; } if (matches) elmt = temp; } } return elmt; } }