Iterate over the children of a given XML node and return the first node that has a specific name. - Java XML

Java examples for XML:XML Node Child

Description

Iterate over the children of a given XML node and return the first node that has a specific name.

Demo Code

/*/*from   www  .  j  a  v a 2s.  co m*/
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You 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.
 *
 */
//package com.java2s;

import org.w3c.dom.Element;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    /**
     * Iterate over the children of a given node and return the first node
     * that has a specific name.
     * @param   parent  the node to search child from. Can be <tt>null</tt>.
     * @param   tagname the child name we are looking for. Cannot be <tt>null</tt>.
     * @return  the first child that matches the given name or <tt>null</tt> if
     *                  the parent is <tt>null</tt> or if a child does not match the
     *                  given name.
     */
    public static Element getChildByTagName(Node parent, String tagname) {
        if (parent == null) {
            return null;
        }
        NodeList childList = parent.getChildNodes();
        final int len = childList.getLength();
        for (int i = 0; i < len; i++) {
            Node child = childList.item(i);
            if (child != null && child.getNodeType() == Node.ELEMENT_NODE
                    && child.getNodeName().equals(tagname)) {
                return (Element) child;
            }
        }
        return null;
    }
}

Related Tutorials