Java tutorial
//package com.java2s; /* * This file is part of McIDAS-V * * Copyright 2007-2015 * Space Science and Engineering Center (SSEC) * University of Wisconsin - Madison * 1225 W. Dayton Street, Madison, WI 53706, USA * http://www.ssec.wisc.edu/mcidas * * All Rights Reserved * * McIDAS-V is built on Unidata's IDV and SSEC's VisAD libraries, and * some McIDAS-V source code is based on IDV and VisAD source code. * * McIDAS-V is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * McIDAS-V 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 Lesser Public License for more details. * * You should have received a copy of the GNU Lesser Public License * along with this program. If not, see http://www.gnu.org/licenses. */ import java.util.ArrayList; import java.util.List; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** * Find all of the descendant elements of the given parent Node * whose tag name.equals the given tag. * * @param parent The root of the xml dom tree to search. * @param tag The tag name to match. * @return The list of descendants that match the given tag. */ public static List<String> findDescendantNamesWithSeparator(Node parent, String tag, String separator) { List<String> found = new ArrayList<>(); findDescendantNamesWithSeparator(parent, tag, "", separator, found); return found; } /** * Find all of the descendant elements of the given parent Node * whose tag name equals the given tag. * * @param parent The root of the xml dom tree to search. * @param tag The tag name to match. * @param found The list of descendants that match the given tag. */ private static void findDescendantNamesWithSeparator(Node parent, String tag, String descendants, String separator, List<String> found) { if (parent instanceof Element) { String elementName = ((Element) parent).getAttribute("name"); if (!elementName.isEmpty()) { descendants += ((Element) parent).getAttribute("name"); } if (parent.getNodeName().equals(tag)) { found.add(descendants); } if (!elementName.isEmpty()) { descendants += separator; } } NodeList children = parent.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); findDescendantNamesWithSeparator(child, tag, descendants, separator, found); } } }