Java XML Element Get by Name getElements(final Element parent, final String name)

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

Description

Get all the direct children elements of an element that have a specific tag name.

License

Open Source License

Parameter

Parameter Description
parent The parent element.
name The tag name to match.

Return

A list of Element's.

Declaration

public static List<Element> getElements(final Element parent, final String name) 

Method Source Code

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

import java.util.LinkedList;
import java.util.List;

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

public class Main {
    /**/*from   w ww.j  a  va 2s . c o m*/
     * Get all the direct children elements of an element.
     *
     * @param parent
     *            The parent element.
     *
     * @return A list of Element's.
     */
    public static List<Element> getElements(final Element parent) {
        final LinkedList<Element> list = new LinkedList<Element>();

        Node node = parent.getFirstChild();

        while (node != null) {
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                list.add((Element) node);
            }

            node = node.getNextSibling();
        }

        return list;
    }

    /**
     * Get all the direct children elements of an element that have a specific
     * tag name.
     *
     * @param parent
     *            The parent element.
     * @param name
     *            The tag name to match.
     *
     * @return A list of Element's.
     */
    public static List<Element> getElements(final Element parent, final String name) {
        final LinkedList<Element> list = new LinkedList<Element>();

        Node node = parent.getFirstChild();

        while (node != null) {
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                final Element element = (Element) node;

                if (element.getTagName().equals(name)) {
                    list.add(element);
                }
            }

            node = node.getNextSibling();
        }

        return list;
    }
}

Related

  1. getElements(Element parent, String localname, String namespaceURI)
  2. getElements(Element parent, String tagName)
  3. getElements(Element parent, String tagName)
  4. getElements(Element parent, String tagName)
  5. getElements(Element parentElement, String nodeName)
  6. getElementsByName(Element parent, String name)
  7. getElementsByTagName(Document doc, String tagName)
  8. getElementsByTagName(Element parent, String name, boolean localOnly)
  9. getElementsByTagName(Element parent, String tagName)