Java XML Element Get getElementByID(Element el, String id)

Here you can find the source of getElementByID(Element el, String id)

Description

get Element By ID

License

Apache License

Declaration

public static Element getElementByID(Element el, String id) 

Method Source Code

//package com.java2s;
/*/* ww w  . java2s  . co  m*/
 * Copyright 2001-2004 The Apache Software Foundation.
 * 
 * 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.
 */

import org.w3c.dom.Attr;

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

public class Main {
    public static Element getElementByID(Element el, String id) {
        if (el == null)
            return null;
        String thisId = el.getAttribute("id");
        if (id.equals(thisId))
            return el;

        NodeList list = el.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            Node node = list.item(i);
            if (node instanceof Element) {
                Element ret = getElementByID((Element) node, id);
                if (ret != null)
                    return ret;
            }
        }

        return null;
    }

    /**
     * Returns the value of an attribute of an element. Returns null
     * if the attribute is not found (whereas Element.getAttribute
     * returns "" if an attrib is not found).
     *
     * @param el       Element whose attrib is looked for
     * @param attrName name of attribute to look for
     * @return the attribute value
     */
    static public String getAttribute(Element el, String attrName) {
        String sRet = null;
        Attr attr = el.getAttributeNode(attrName);

        if (attr != null) {
            sRet = attr.getValue();
        }
        return sRet;
    }
}

Related

  1. getElementAttributeValue(Document doc, String tagName, String attributeName)
  2. getElementBooleanValue(Document document, Element parent, String element)
  3. getElementByClass(Element ele, String name)
  4. getElementByFilter(Document doc, NodeFilter filter)
  5. getElementByID(Element el, String id)
  6. getElementById(Element element, String id)
  7. getElementByName(Element ele, String name)
  8. getElementByQualifiedName(Element n, String namespace, String elementName)
  9. getElementByTagName(Element current, String name)