Java XML Child Get by Name getChildElement(Node parent, String name)

Here you can find the source of getChildElement(Node parent, String name)

Description

Returns a node child with the specified tag name of the specified parent node, or null if no such child node is found.

License

Educational Community License

Parameter

Parameter Description
parent the parent node
name the name of the child node

Return

child node if found, null otherwise

Declaration

public static Element getChildElement(Node parent, String name) 

Method Source Code

//package com.java2s;
/**//w w  w.  j a va 2s  .  c om
 * Copyright 2005-2015 The Kuali Foundation
 *
 * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
 *
 * 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 org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    /**
     * Returns a node child with the specified tag name of the specified parent node,
     * or null if no such child node is found. 
     * @param parent the parent node
     * @param name the name of the child node
     * @return child node if found, null otherwise
     */
    public static Element getChildElement(Node parent, String name) {
        NodeList childList = parent.getChildNodes();
        for (int i = 0; i < childList.getLength(); i++) {
            Node node = childList.item(i);
            // we must test against NodeName, not just LocalName
            // LocalName seems to be null - I am guessing this is because
            // the DocumentBuilderFactory is not "namespace aware"
            // although I would have expected LocalName to default to
            // NodeName
            if (node.getNodeType() == Node.ELEMENT_NODE
                    && (name.equals(node.getLocalName()) || name.equals(node.getNodeName()))) {
                return (Element) node;
            }
        }
        return null;
    }
}

Related

  1. getChildElement(Node node)
  2. getChildElement(Node node, String childName)
  3. getChildElement(Node parent, String childLocalName, String childNamespaceURI)
  4. getChildElement(Node parent, String childName)
  5. getChildElement(Node parent, String elementName)
  6. getChildElement(Node start, String name)
  7. getChildElement(NodeList childs, Node parent)
  8. getChildElement(String name, Element el)
  9. getChildElement(String name, Element elem)