Java XML Child Get by Name getChildElement(Element element, String elementName)

Here you can find the source of getChildElement(Element element, String elementName)

Description

Returns the first child element with the specified name, or null if none exists.

License

Open Source License

Parameter

Parameter Description
element a parameter
elementName a parameter

Return

Element

Declaration

public static Element getChildElement(Element element, String elementName) 

Method Source Code

//package com.java2s;

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

public class Main {
    /**/*from   w  w  w.ja  va 2s . c o  m*/
     * Returns the first child element with the specified name, or null if none exists.
     * @param element
     * @param elementName
     * @return Element
     */
    public static Element getChildElement(Element element, String elementName) {
        for (Node node = element.getFirstChild(); node != null; node = node.getNextSibling()) {
            if (node instanceof Element) {
                Element childElem = (Element) node;
                String elemName = getElementName(childElem);

                if (elementName.equals(elemName))
                    return childElem;
            }
        }

        return null;
    }

    /**
     * Returns the element name of the given element.
     * @param element
     * @return String
     */
    public static String getElementName(Element element) {
        // When loading from disk the local name will be setup correctly, but if the local name
        // is fetched directly after calling Document.createElement() then the value will be null.
        // See the JavaDoc for more info.  To workaround this, use the complete node name.
        String elemName = element.getLocalName();
        if (elemName == null) {
            elemName = element.getNodeName();
        }
        return elemName;
    }
}

Related

  1. getChildElement(Element el, String tagName)
  2. getChildElement(Element el, String tagName)
  3. getChildElement(Element ele, String childName)
  4. getChildElement(Element elem, String name)
  5. getChildElement(Element element, String childName)
  6. getChildElement(Element element, String name)
  7. GetChildElement(Element element, String name)
  8. getChildElement(Element element, String tagName)
  9. getChildElement(Element element, String tagName)