Java tutorial
//package com.java2s; /* Copyright 2013, 2016 Nationale-Nederlanden Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import java.util.Collection; import java.util.LinkedList; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** * Method getChildTags. Get all direct children of given element which * match the given tag. * This method only looks at the direct children of the given node, and * doesn't descent deeper into the tree. If a '*' is passed as tag, * all elements are returned. * * @param el Element where to get children from * @param tag Tag to match. Use '*' to match all tags. * @return Collection Collection containing all elements found. If * size() returns 0, then no matching elements * were found. All items in the collection can * be safely cast to type * <code>org.w3c.dom.Element</code>. */ public static Collection<Node> getChildTags(Element el, String tag) { Collection<Node> c; NodeList nl; int len; boolean allChildren; c = new LinkedList<Node>(); nl = el.getChildNodes(); len = nl.getLength(); if ("*".equals(tag)) { allChildren = true; } else { allChildren = false; } for (int i = 0; i < len; i++) { Node n = nl.item(i); if (n instanceof Element) { Element e = (Element) n; if (allChildren || e.getTagName().equals(tag)) { c.add(n); } } } return c; } }