Java XML Child Get by Name getChildElement(Element ele, String childName)

Here you can find the source of getChildElement(Element ele, String childName)

Description

Utility method that returns the first child element identified by its getName.

License

Open Source License

Parameter

Parameter Description
ele the DOM element to analyze
childName the child element getName to look for

Return

the org.w3c.dom.Element creating, or null if none found

Declaration

public static Element getChildElement(Element ele, String childName) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import org.w3c.dom.Element;

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

public class Main {
    /**//from w  w w  . j  a va 2s. c o  m
     * Utility method that returns the first child element
     * identified by its getName.
     * @param ele the DOM element to analyze
     * @param childName the child element getName to look for
     * @return the <code>org.w3c.dom.Element</code> creating,
     * or <code>null</code> if none found
     */
    public static Element getChildElement(Element ele, String childName) {
        NodeList nl = ele.getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            if (node instanceof Element && nodeNameEquals(node, childName))
                return (Element) node;
        }
        return null;
    }

    /**
     * Namespace-aware equals comparison. Returns <code>true</code> if either
     * {@link Node#getLocalName} or {@link Node#getNodeName} equals <code>desiredName</code>,
     * otherwise returns <code>false</code>.
     */
    public static boolean nodeNameEquals(Node node, String desiredName) {
        assert node != null : "Node must not be null";
        assert desiredName != null : "Desired getName must not be null";
        return desiredName.equals(node.getNodeName())
                || desiredName.equals(node.getLocalName());
    }
}

Related

  1. getChildDoubleByName(Node node, String nodeName, double errValue)
  2. getChildElemByTagName(Element parent, String tagName)
  3. getChildElement(Element currentNode, String nsURI, String localName)
  4. getChildElement(Element el, String tagName)
  5. getChildElement(Element el, String tagName)
  6. getChildElement(Element elem, String name)
  7. getChildElement(Element element, String childName)
  8. getChildElement(Element element, String elementName)
  9. getChildElement(Element element, String name)