Java XML Element Get by Name getElementByTagNameWithParents(Element n, String... elementName)

Here you can find the source of getElementByTagNameWithParents(Element n, String... elementName)

Description

Gets the first child Element with a given name

License

Apache License

Parameter

Parameter Description
n the node get the children from
elementName the name of the child elements

Return

the first child Element with a given name

Declaration

public static Element getElementByTagNameWithParents(Element n, String... elementName) 

Method Source Code

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

import java.util.ArrayList;

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

public class Main {
    /**//from  ww  w  . ja  v a 2  s  .c o m
     * Gets the first child Element with a given name
     * 
     * @param n
     *            the node get the children from
     * @param elementName
     *            the name of the child elements
     * @return the first child Element with a given name
     */
    public static Element getElementByTagNameWithParents(Element n, String... elementName) {
        for (String elName : elementName) {
            Element subEl = getElementByTagName(n, elName);
            if (subEl == null)
                return null;
            n = subEl;
        }
        return n;
    }

    public static Element getElementByTagName(Element n, String elementName) {
        int sz = n.getChildNodes().getLength();
        ArrayList<Element> elements = new ArrayList<Element>(sz);
        for (int idx = 0; idx < sz; idx++) {
            Node node = n.getChildNodes().item(idx);
            if (node instanceof Element && node.getLocalName().equals(elementName))
                elements.add((Element) node);
        }
        if (elements.size() > 0)
            return elements.get(0);
        return null;
    }
}

Related

  1. getElementByTagName(Document doc, String eleName)
  2. getElementByTagName(Document document, String tagName)
  3. getElementByTagName(Element aParent, String aName)
  4. getElementByTagName(Element parent, String elementName)
  5. getElementByTagName(Element parent, String elementName)
  6. getElementDateValue(Document document, Element parent, String string)
  7. getElementFloatValue(Document document, Element parent, String element)
  8. getElements(Element parent, String localName)
  9. getElements(Element parent, String localname, String namespaceURI)