Java XML Child Get by Name getChildByName(final Element parent, final String name)

Here you can find the source of getChildByName(final Element parent, final String name)

Description

Gets the child by name.

License

Open Source License

Parameter

Parameter Description
parent the parent
name the name

Return

the child by name

Declaration

public static Element getChildByName(final Element parent, final String name) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2006-2010 eBay Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *******************************************************************************/

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

public class Main {
    /**/*from  w  w w  . ja  va 2  s .  c o m*/
     * Gets the child by name.
     *
     * @param parent the parent
     * @param name the name
     * @return the child by name
     */
    public static Element getChildByName(final Element parent, final String name) {
        if (parent == null || name == null)
            return null;
        final NodeList list = parent.getChildNodes();
        for (int k = 0, listCount = list.getLength(); k < listCount; k++) {
            final Node child = list.item(k);
            if (child.getNodeType() == Node.ELEMENT_NODE && nodeNameEqualToWithNoNamespace(child, name))
                return (Element) child;
        }
        return null;
    }

    /**
     * Node name equal to with no namespace.
     *
     * @param node the node
     * @param target the target
     * @return true, if successful
     */
    public static boolean nodeNameEqualToWithNoNamespace(final Node node, final String target) {
        if (node == null || target == null)
            return false;
        String name = node.getNodeName();
        final int index = name.indexOf(':');
        if (index >= 0)
            name = name.substring(index + 1); // Strip namespace
        return name.equals(target);
    }
}

Related

  1. getChildByName(Element parent, String name)
  2. getChildByName(Element parent, String name)
  3. getChildByName(final Element parent, final String name)
  4. getChildByName(Node node, String name)
  5. getChildByName(Node node, String name)
  6. getChildByName(Node node, String name)