Java XML First Child Element getFirstChildElementByName(final Element parent, final String name)

Here you can find the source of getFirstChildElementByName(final Element parent, final String name)

Description

Returns the first element in the parent that match the specified name.

License

Open Source License

Parameter

Parameter Description
parent the parent element
name the expected name of the childs

Return

the first element if there is a match, otherwise

Declaration

public static Optional<Element> getFirstChildElementByName(final Element parent, final String name) 

Method Source Code


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

import java.util.ArrayList;

import java.util.List;
import java.util.Optional;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class Main {
    /**//ww  w  .j av  a  2  s .c om
     * Returns the first element in the parent that match the specified name.
     *
     * @param parent
     *         the parent element
     * @param name
     *         the expected name of the childs
     *
     * @return the first element if there is a match, {@link Optional#empty()} otherwise
     */
    public static Optional<Element> getFirstChildElementByName(final Element parent, final String name) {
        return getChildElementsByName(parent, name).stream().findFirst();
    }

    /**
     * Returns all elements in the parent that match the specified name.
     *
     * @param parent
     *         the parent element
     * @param name
     *         the expected name of the childs
     *
     * @return the elements, the list might be empty if there is no match
     */
    public static List<Element> getChildElementsByName(final Element parent, final String name) {
        List<Element> elements = new ArrayList<Element>();
        if (parent != null) {
            Node child = parent.getFirstChild();
            while (child != null) {
                if (child.getNodeType() == Node.ELEMENT_NODE && child.getNodeName().equals(name)) {
                    elements.add((Element) child);
                }
                child = child.getNextSibling();
            }
        }
        return elements;
    }
}

Related

  1. getFirstChildElement(Node rootNode)
  2. getFirstChildElement(Node start)
  3. getFirstChildElementByLocalName(Element parentElem, String localName)
  4. getFirstChildElementByName(Element parent, String tagName)
  5. getFirstChildElementByName(Element root, String tagName)
  6. getFirstChildElementByName(Node node, String name)
  7. getFirstChildElementByTagName(Element element, String name)
  8. getFirstChildElementByTagName(Node element, String tagName)
  9. getFirstChildElementCaseInsensitive(Element root, String elementName)