Java XML Element Get by Name getElement(Element parent, String tagName)

Here you can find the source of getElement(Element parent, String tagName)

Description

Gets the immediately descendant element from the parent element.

License

Apache License

Parameter

Parameter Description
parent the parent element in the element tree
tagName the specified tag name.

Return

immediately descendant element of parent element, NULL otherwise.

Declaration

public static Element getElement(Element parent, String tagName) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

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

import java.util.ArrayList;
import java.util.List;

public class Main {
    /**// ww w . j  av  a2  s .c om
     * Gets the immediately descendant element from the parent element.
     *
     * @param parent
     *          the parent element in the element tree
     * @param tagName
     *          the specified tag name.
     * @return immediately descendant element of parent element, NULL otherwise.
     */
    public static Element getElement(Element parent, String tagName) {
        List<Element> children = getElements(parent, tagName);

        if (children.isEmpty()) {
            return null;
        } else {
            return children.get(0);
        }
    }

    /**
     * Gets the descendant elements list from the parent element.
     *
     * @param parent
     *          the parent element in the element tree
     * @param tagName
     *          the specified tag name
     * @return the NOT NULL descendant elements list
     */
    public static List<Element> getElements(Element parent, String tagName) {
        NodeList nodes = parent.getElementsByTagName(tagName);
        List<Element> elements = new ArrayList<>();

        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            if (node instanceof Element) {
                elements.add((Element) node);
            }
        }

        return elements;
    }
}

Related

  1. getElement(Document parent, String name)
  2. getElement(Element parent, String elementName)
  3. getElement(Element parent, String elementName)
  4. getElement(Element parent, String localname, int position)
  5. getElement(Element parent, String tagName)
  6. getElement(Element parentElement, String nodeName)
  7. getElement(Node parent, int index)
  8. getElement(String elementName, Element parentElement)
  9. getElement(String name, int index, Element parent)