Java XML First Child Element getFirstLevelChildElementByTagName(Element parent, String elementName)

Here you can find the source of getFirstLevelChildElementByTagName(Element parent, String elementName)

Description

Get the immediate child element with a given tag name.

License

Open Source License

Parameter

Parameter Description
parent Parent Element
elementName Tag name of the child elements to be returned.

Return

First child element which has the given tag name.

Declaration

public static final Element getFirstLevelChildElementByTagName(Element parent, String elementName) 

Method Source Code

//package com.java2s;

import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class Main {
    /**// w  ww . j a v a2s  .  c  o  m
     * Get the immediate child element with a given tag name. If multiple child elements exist with the same tag name,
     * the first child element is returned.
     * 
     * @param parent
     *            Parent Element
     * @param elementName
     *            Tag name of the child elements to be returned.
     * 
     * @return First child element which has the given tag name.
     */
    public static final Element getFirstLevelChildElementByTagName(Element parent, String elementName) {
        Node childNode = parent.getFirstChild();
        while (childNode != null) {
            if ((childNode.getNodeType() == Node.ELEMENT_NODE)
                    && ((Element) childNode).getLocalName().equals(elementName)) {
                return (Element) childNode;
            }
            childNode = childNode.getNextSibling();
        }
        return null;
    }
}

Related

  1. getFirstElementChild(final Node node)
  2. getFirstElementChild(final Node node)
  3. getFirstElementChild(Node root)
  4. getFirstElementContent(Element element, String childName)
  5. getFirstElemText(Element parent, String childName)
  6. getFirstLevelChildElementByTagName(Element parent, String elementName)
  7. getFirstLevelChildElements(Element parent)
  8. getFirstLevelChildElements(Element parent)
  9. getFirstLevelChildElementsByTagName(Element parent, String elementName)