Java XML Child Get by Name getChildElement(final Node parent, final String name)

Here you can find the source of getChildElement(final Node parent, final String name)

Description

Look for child node of given name.

License

Open Source License

Parameter

Parameter Description
parent Node where to start.
name Name of the node to look for.

Return

Returns Element or null.

Declaration

public static final Element getChildElement(final Node parent, final String name) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2015-2016 Oak Ridge National Laboratory.
 * 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
 *******************************************************************************/

import org.w3c.dom.Element;

import org.w3c.dom.Node;

public class Main {
    /** Look for child node of given name.
     */*from  w  w w.  j  ava 2s .  c om*/
     *  @param parent Node where to start.
     *  @param name Name of the node to look for.
     *  @return Returns Element or <code>null</code>.
     */
    public static final Element getChildElement(final Node parent, final String name) {
        return findElementByName(parent.getFirstChild(), name);
    }

    /** Look for Element node of given name.
     *
     *  <p>Checks the node itself and its siblings for an {@link Element}.
     *  Does not descent down the 'child' links.
     *
     *  @param node Node where to start.
     *  @param name Name of the node to look for.
     *  @return Returns node, the next matching sibling, or <code>null</code>.
     */
    private static final Element findElementByName(Node node, final String name) {
        while (node != null) {
            if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals(name))
                return (Element) node;
            node = node.getNextSibling();
        }
        return null;
    }
}

Related

  1. getChildElement(Element root, String name)
  2. getChildElement(Element root, String name, boolean mandatory)
  3. getChildElement(final Element element, final String namespace, final String tagName)
  4. getChildElement(final Element parent, final String childName)
  5. getChildElement(final Element parent, final String ns, final String localName)
  6. getChildElement(final Node parentNode, final String childNodeName)
  7. getChildElement(Node node)
  8. getChildElement(Node node, String childName)
  9. getChildElement(Node parent, String childLocalName, String childNamespaceURI)