Java XML Element Find findElementWithId(String id, Element root)

Here you can find the source of findElementWithId(String id, Element root)

Description

fast search for Element with id attribute

License

Common Public License

Parameter

Parameter Description
root the root Element of the search. search will cover root and its descendants
id the id to search for

Return

null or the element

Declaration

public static Element findElementWithId(String id, Element root) 

Method Source Code

//package com.java2s;
/*//w ww. j ava  2 s.  co  m
 * ====================================================================
 * This software is subject to the terms of the Common Public License
 * Agreement, available at the following URL:
 *   http://www.opensource.org/licenses/cpl.html .
 * Copyright (C) 2003-2004 TONBELLER AG.
 * All Rights Reserved.
 * You must accept the terms of that agreement to use this software.
 * ====================================================================
 *
 * 
 */

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

public class Main {
    /**
     * fast search for Element with id attribute
     * @param root the root Element of the search. search will cover root and 
     * its descendants
     * @param id the id to search for
     * @return null or the element
     */
    public static Element findElementWithId(String id, Element root) {
        if (id.equals(root.getAttribute("id")))
            return root;
        NodeList list = root.getChildNodes();
        int len = list.getLength();
        for (int i = 0; i < len; i++) {
            Node n = list.item(i);
            if (n.getNodeType() != Node.ELEMENT_NODE)
                continue;
            Element child = (Element) list.item(i);
            Element found = findElementWithId(id, child);
            if (found != null)
                return found;
        }
        return null;
    }
}

Related

  1. findElement(Element root, String localName, String namespace)
  2. findElement(Element topElm, String localName, String namespace)
  3. findElement(final Element e, final String find)
  4. findElement(final String idValue, final String idTagName, final String tagName, final Element root)
  5. findElementAsString(final Element e, final String find)
  6. findNodesByType(Element topElm, int type)
  7. findNodeValue(Element firstElement, String name)
  8. getAllElements(Element config, String elementName)
  9. getAllElements(Element element)