Java tutorial
//package com.java2s; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** * Finds a node in a document and returns the value from an attribute of * this node. If there are multiple nodes with the specified tag name, the * attribute value of the first node found will be returned. * * @param document * the document. * @param nodeName * the name of the node . * @param attributeName * the name of the node's attribute. * @return the value of the node's attribute or <code>null</code> if either * no node with the specified tag name or no attribute with the * specified attribute name could be found. */ public static String getAttributeValueFromNode(Document document, String nodeName, String attributeName) { Node node = getNode(document, nodeName); if (node != null) { Node attribute = getAttributeValue(node, attributeName); if (attribute != null) { return attribute.getNodeValue(); } } return null; } /** * Gets the first node with the specified tag name from the given document. * If there are multiple nodes with the specified tag name, the first node * found will be returned. * * @param doc * the document * @param tagname * the tag name of the node to find. * @return the first node found with the specified tag name or * <code>null</code> if no node with that name could be found. */ public static Node getNode(Document doc, String tagname) { NodeList nl = doc.getElementsByTagName(tagname); if (!isEmpty(nl)) { return nl.item(0); } return null; } /** * Gets the value from a node's attribute. * * @param node * the node. * @param attributeName * the name of the attribute. * @return the value of the attribute with the specified name or * <code>null</code> if there is no attribute with that name. */ public static Node getAttributeValue(Node node, String attributeName) { return (node.hasAttributes()) ? node.getAttributes().getNamedItem(attributeName) : null; } /** * Null-safe check if a nodelist is empty. * * @param nodeList * the nodelist to check. * @return <code>true</code> if the given nodelist is <code>null</code> or * empty. */ public static boolean isEmpty(NodeList nodeList) { return nodeList == null || nodeList.getLength() == 0; } }