Java XML First Child Element getFirstChildElement(Element parent, String tagName)

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

Description

Gets the first child Element of the given parent Element that has the given tag name.

License

Open Source License

Parameter

Parameter Description
parent The parent Element
tagName The tag name the child Element must have. May be null. Then the first child element with any name is returned.

Return

The first child of the given parent having given tag name.

Declaration

public static Element getFirstChildElement(Element parent, String tagName) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2010-2015 BSI Business Systems Integration AG.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors://from   w w  w .  j  a  va  2s. co m
 *     BSI Business Systems Integration AG - initial API and implementation
 ******************************************************************************/

import org.w3c.dom.Element;

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

public class Main {
    /**
     * Gets the first child {@link Element} of the given parent {@link Element} that has the given tag name.
     *
     * @param parent
     *          The parent {@link Element}
     * @param tagName
     *          The tag name the child {@link Element} must have. May be null. Then the first child element with any name
     *          is returned.
     * @return The first child {@link Element} of the given parent {@link Element} having given tag name.
     */
    public static Element getFirstChildElement(Element parent, String tagName) {
        NodeList children = null;
        if (tagName == null) {
            children = parent.getChildNodes();
        } else {
            children = parent.getElementsByTagName(tagName);
        }
        for (int i = 0; i < children.getLength(); i++) {
            Node n = children.item(i);
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                return (Element) n;
            }
        }
        return null;
    }
}

Related

  1. getFirstChildElement(Element parent)
  2. getFirstChildElement(Element parent)
  3. getFirstChildElement(Element parent)
  4. getFirstChildElement(Element parent, String childName)
  5. getFirstChildElement(Element parent, String nsUri, String localPart)
  6. getFirstChildElement(Element parent, String tagName)
  7. getFirstChildElement(Element parentElem)
  8. getFirstChildElement(Element root)
  9. getFirstChildElement(final Node node)