Java tutorial
//package com.java2s; /*--------------------------------------------------------------- * Copyright 2005 by the Radiological Society of North America * * This source software is released under the terms of the * RSNA Public License (http://mirc.rsna.org/rsnapubliclicense) *----------------------------------------------------------------*/ import java.util.ArrayList; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** * Get an array of specific attributes for specific elements * in a Node tree. If the node is a Document, use the document * element as the starting point. * @param node the top of the tree to search. * @param nodeName the element names to include in the search. * @param attrName the name of the attributes to include. * @return the array of attribute values natching the criteria. */ public static String[] getAttributeValues(Node node, String nodeName, String attrName) { if (node instanceof Document) node = ((Document) node).getDocumentElement(); if (!(node instanceof Element)) return new String[0]; NodeList nodeList = ((Element) node).getElementsByTagName(nodeName); ArrayList list = new ArrayList(); for (int i = 0; i < nodeList.getLength(); i++) { Attr attr = ((Element) nodeList.item(i)).getAttributeNode(attrName); if (attr != null) list.add(attr.getValue()); } String[] values = new String[list.size()]; return (String[]) list.toArray(values); } }