Java tutorial
//package com.java2s; /* $HeadURL:: $ * $Id$ * * Copyright (c) 2006-2008 by Topaz, Inc. * http://topazproject.org * * 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.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** * Get a single child element with the given name. If more than one child with the given name * exists, a warning is logged. * * @param parent the parent node * @param name the name of the child element to get; may be null or "*" to indicate any * element child * @param log where to write the warning if more than one child element was found; may be * null to disable the warning * @return the child, or null if none was found */ public static Element getOnlyChild(Element parent, String name, Log log) { NodeList children = getChildren(parent, name); if (children.getLength() == 0) return null; if (children.getLength() > 1 && log != null) log.warn("Expected exactly one child named '" + name + "' of '" + parent.getTagName() + "' but got " + children.getLength()); return (Element) children.item(0); } /** * Get all immediate element children with the given name. This differs from {@link * org.w3c.dom.Element#getElementsByTagName getElementsByTagName} in that this only returns * direct children, not all descendents. * * @param parent the parent node * @param childName the name of the children elements to get; may be null or "*" to indicate all * element children * @return the list of children; may be empty */ public static NodeList getChildren(Element parent, String childName) { final NodeList children = parent.getChildNodes(); final String filter = (childName != null && !childName.equals("*")) ? childName : null; return new NodeList() { private List elems; { elems = new ArrayList(); for (int idx = 0; idx < children.getLength(); idx++) { Node n = children.item(idx); if (n.getNodeType() == Node.ELEMENT_NODE && (filter == null || n.getNodeName().equals(filter))) elems.add(n); } } public Node item(int index) { return (Node) elems.get(index); } public int getLength() { return elems.size(); } }; } }