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

get Child By Name

License

Open Source License

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 
 *    /*from   ww w.  j a v a  2  s.c o m*/
 *        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 {
    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;
    }

    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)
  7. getChildByName(Node node, String nodeName)