Java XML Element Get getElementByTagName(Element element, String tag)

Here you can find the source of getElementByTagName(Element element, String tag)

Description

get single element by tag name.

License

Open Source License

Parameter

Parameter Description
element the element
tag the tag

Return

the element by tag name

Declaration

public static Element getElementByTagName(Element element, String tag) 

Method Source Code

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

import java.util.ArrayList;

import java.util.List;

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

public class Main {
    /**//w  w w . ja v a  2  s  .  c o  m
     * get single element by tag name.
     *
     * @param element the element
     * @param tag the tag
     * @return the element by tag name
     */
    public static Element getElementByTagName(Element element, String tag) {
        NodeList list = element.getElementsByTagName(tag);
        for (int i = 0; i < list.getLength(); i++) {
            Node node = list.item(i);
            if (node instanceof Element) {
                return (Element) node;
            }
        }
        return null;
    }

    /**
     * get single element by tag name.
     *
     * @param element the element
     * @param tag the tag
     * @return the elements by tag name
     */
    public static List<Element> getElementsByTagName(Element element,
            String tag) {
        List<Element> elements = new ArrayList<Element>();
        NodeList list = element.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            if (list.item(i) instanceof Element) {
                Element e = (Element) list.item(i);
                if (e.getTagName().equals(tag)) {
                    elements.add(e);
                }
            }
        }
        return elements;
    }
}

Related

  1. getElementByTagName(Element el, String tag)
  2. getElementByTagName(Element el, String tag)
  3. getElementByTagName(Element elem, String name, String emptyValue)
  4. getElementByTagName(Element element, String name)
  5. getElementByTagName(Element element, String name, int index)
  6. getElementByTagName(Element element, String tag)
  7. getElementByTagName(Element n, String elementName)
  8. getElementContent(Element e)
  9. getElementContent(Element elem)