Java XML Child Get by Name getChildElement(Element parentElement, String childElementName)

Here you can find the source of getChildElement(Element parentElement, String childElementName)

Description

get Child Element

License

Open Source License

Parameter

Parameter Description
parentElement a parameter
childElementName a parameter

Return

the element if it exists, null otherwise

Declaration

public static Element getChildElement(Element parentElement, String childElementName) 

Method Source Code

//package com.java2s;
/******************************************************************************
 * Copyright (c) 2008-2013, Linagora/*from   ww  w .java 2  s.com*/
 *
 * 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:
 *       Linagora - initial API and implementation
 *******************************************************************************/

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

public class Main {
    /**
     * @param parentElement
     * @param childElementName
     * @return the element if it exists, null otherwise
     */
    public static Element getChildElement(Element parentElement, String childElementName) {

        NodeList children = parentElement.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if (child.getNodeType() == Node.ELEMENT_NODE && childElementName.equals(getNodeName(child)))
                return (Element) child;
        }

        return null;
    }

    /**
     * @param node
     * @return the name of the XML node (with no name space element)
     */
    public static String getNodeName(Node node) {

        String name = node.getNamespaceURI() != null ? node.getLocalName() : node.getNodeName();
        if (name.contains(":")) { //$NON-NLS-1$
            String[] parts = name.split(":"); //$NON-NLS-1$
            name = parts[parts.length - 1];
        }

        return name;
    }
}

Related

  1. getChildElement(Element parent, String tagName)
  2. getChildElement(Element parent, String tagName)
  3. getChildElement(Element parent, String tagName)
  4. getChildElement(Element parent, String tagName)
  5. getChildElement(Element parent, String tagName)
  6. getChildElement(Element parentElement, String name)
  7. getChildElement(Element parentElement, String tagName)
  8. getChildElement(Element root, String name)
  9. getChildElement(Element root, String name, boolean mandatory)