Java XML Child Get getChild(final Element parent, final String tag)

Here you can find the source of getChild(final Element parent, final String tag)

Description

Get child node with given tag name.

License

Open Source License

Declaration

public static Element getChild(final Element parent, final String tag) 

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   w ww.j a va 2 s . co 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 {
    /**
     * Get child node with given tag name.
     * Return null if no child can be found.
     */
    public static Element getChild(final Element parent, final String tag) {
        if (parent == null || tag == 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 && nodeNameEqualTo(child, tag))
                return (Element) child;
        }
        return null;
    }

    /**
     * Check whether a name of given node is equal to a given name.
     * Strips namespace (if any). Case-sensitive.
     */
    public static boolean nodeNameEqualTo(final Node node, final String target) {
        if (node == null || target == null)
            return false;
        String name = node.getNodeName();
        if (target.indexOf(':') < 0) { // If target contains namespace, require exact match
            final int index = name.indexOf(':');
            if (index >= 0)
                name = name.substring(index + 1); // Strip namespace
        }
        return name.equals(target);
    }
}

Related

  1. getChild(Element parent, String name)
  2. getChild(Element parent, String name)
  3. getChild(Element parentEl, String name)
  4. getChild(Element root, String... path)
  5. getChild(final Element element, final String tagName)
  6. getChild(final Element root, final String name)
  7. getChild(final Element root, final String name)
  8. getChild(Node n, String name)
  9. getChild(Node node, String name)