Java XML First Child Element getFirstNamedChild(Node node, String name)

Here you can find the source of getFirstNamedChild(Node node, String name)

Description

Get the first child element with a specified name.

License

Open Source License

Parameter

Parameter Description
node the starting node.
name the name of the child to find.

Return

the first child element with the specified name, or null if the starting node is null or if no child with the name exists.

Declaration

public static Element getFirstNamedChild(Node node, String name) 

Method Source Code

//package com.java2s;
/*---------------------------------------------------------------
*  Copyright 2011 by the Radiological Society of North America
*
*  This source software is released under the terms of the
*  RSNA Public License (http://mirc.rsna.org/rsnapubliclicense)
*----------------------------------------------------------------*/

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import org.w3c.dom.Node;

public class Main {
    /**//  w  ww. j  a va2 s. c  o m
     * Get the first child element with a specified name.
     * If the starting node is a Document, use the document element
     * as the starting point. Only first-generation children of the
     * starting node are searched.
     * @param node the starting node.
     * @param name the name of the child to find.
     * @return the first child element with the specified name, or null
     * if the starting node is null or if no child with the name exists.
     */
    public static Element getFirstNamedChild(Node node, String name) {
        if (node == null)
            return null;
        if (node instanceof Document)
            node = ((Document) node).getDocumentElement();
        if (!(node instanceof Element))
            return null;
        Node child = node.getFirstChild();
        while (child != null) {
            if ((child instanceof Element) && child.getNodeName().equals(name)) {
                return (Element) child;
            }
            child = child.getNextSibling();
        }
        return null;
    }
}

Related

  1. getFirstLevelChildElementsByTagName(Element parent, String elementName)
  2. getFirstLevelChildElementsByTagName(Element parent, String elementName)
  3. getFirstMatchedValueByChildTagName(Node parent, String name)
  4. getFirstMatchingDeepChildByTagName(final Element e, final String tagName)
  5. getFirstNamedChild(Node n, String name)
  6. getFirstNamedChildNode(Element element, String string)
  7. getFirstNamedChildNode(Node root, String nodeName)
  8. getFirstNontextChild(Node d)
  9. getFirstNonTextChild(Node root)