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

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

Description

get Child Element

License

Apache License

Declaration

public static Element getChildElement(Element parent, String name) 

Method Source Code

//package com.java2s;
/*/* ww w. java  2  s .c o m*/
 * Copyright 2013 Keith D Swenson
 *
 * 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
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Contributors Include: Shamim Quader, Sameer Pradhan, Kumar Raja, Jim Farris,
 * Sandia Yang, CY Chen, Rajiv Onat, Neal Wang, Dennis Tam, Shikha Srivastava,
 * Anamika Chaudhari, Ajay Kakkar, Rajeev Rastogi
 */

import org.w3c.dom.Element;

import org.w3c.dom.NodeList;

public class Main {
    public static Element getChildElement(Element parent, String name) {
        NodeList childNdList = parent.getChildNodes();
        if (childNdList == null) {
            return null;
        }
        for (int i = 0; i < childNdList.getLength(); i++) {
            org.w3c.dom.Node n = childNdList.item(i);

            if (n == null) {
                //apparently, there is some situations where the Nodellist will return
                //a null.  Have gotten a null opinter exception on the line below.
                //don't understand how it happens, but this seems to happen, just skip it.
                continue;
            }

            if (n.getNodeType() != org.w3c.dom.Node.ELEMENT_NODE) {
                continue;
            }
            if (name.equals(n.getLocalName())) {
                return (Element) n;
            }
            if (name.equals(n.getNodeName())) {
                return (Element) n;
            }
        }
        return null;
    }
}

Related

  1. getChildElement(Element element, String tagName)
  2. getChildElement(Element element, String tagName)
  3. getChildElement(Element parent, String childName)
  4. getChildElement(Element parent, String childName)
  5. getChildElement(Element parent, String element)
  6. getChildElement(Element parent, String name)
  7. getChildElement(Element parent, String name)
  8. getChildElement(Element parent, String tagName)
  9. getChildElement(Element parent, String tagName)