Java XML Child Get by Name getChildElement(String name, Element el)

Here you can find the source of getChildElement(String name, Element el)

Description

Gets the given element's first child DOM element with the specified name.

License

Open Source License

Declaration

public static Element getChildElement(String name, Element el) 

Method Source Code

//package com.java2s;

import org.w3c.dom.*;

public class Main {
    /**//from   w  ww  .  ja v  a 2  s  . co  m
     * Gets the given element's first child DOM element with the specified name.
     */
    public static Element getChildElement(String name, Element el) {
        if (name == null || el == null)
            return null;
        NodeList list = el.getChildNodes();
        int size = list.getLength();
        for (int i = 0; i < size; i++) {
            Node node = list.item(i);
            if (!(node instanceof Element))
                continue;
            if (name.equals(getName(node)))
                return (Element) node;
        }
        return null;
    }

    /**
     * Gets the given element's index-th child DOM element with the specified
     * name, or the index-th child element overall if name is null.
     */
    public static Element getChildElement(String name, Element el, int index) {
        if (el == null)
            return null;
        NodeList list = el.getChildNodes();
        int size = list.getLength();
        String cName = ":" + name;
        int q = 0;
        for (int i = 0; i < size; i++) {
            Node node = list.item(i);
            if (!(node instanceof Element))
                continue;
            String nodeName = node.getNodeName();
            if (name == null || nodeName.equals(name) || nodeName.endsWith(cName)) {
                if (q == index)
                    return (Element) node;
                q++;
            }
        }
        return null;
    }

    /** Gets the local (sans namespace) name of the given node. */
    public static String getName(Node node) {
        // NB: The node.getLocalName() method does not work.
        String name = node.getNodeName();
        int colon = name.lastIndexOf(":");
        return colon < 0 ? name : name.substring(colon + 1);
    }
}

Related

  1. getChildElement(Node parent, String childName)
  2. getChildElement(Node parent, String elementName)
  3. getChildElement(Node parent, String name)
  4. getChildElement(Node start, String name)
  5. getChildElement(NodeList childs, Node parent)
  6. getChildElement(String name, Element elem)
  7. getChildElements(Element element, String childrenName)
  8. getChildElements(Element element, String namespace, String localName)
  9. getChildElements(Element element, String tag)