Java XML Element Get getElementById(Element element, String id)

Here you can find the source of getElementById(Element element, String id)

Description

get Element By Id

License

Open Source License

Declaration

public static Element getElementById(Element element, String id) 

Method Source Code


//package com.java2s;
/*//ww  w.j  ava  2s. c  o m
 * Copyright (C) 2010  Just Objects B.V.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import org.w3c.dom.*;

public class Main {
    public static Element getElementById(Document document, String id) {
        return getElementById(document.getDocumentElement(), id);
    }

    public static Element getElementById(Element element, String id) {
        return getElementById(element.getChildNodes(), id);
    }

    /**
     * Get Element that has attribute id="xyz".
     */
    public static Element getElementById(NodeList nodeList, String id) {
        // Note we should really use the Query here !!

        Element element = null;
        int len = nodeList.getLength();
        for (int i = 0; i < len; i++) {
            Node node = (Node) nodeList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                element = (Element) node;
                if (((Element) node).getAttribute("id").equals(id)) {
                    // found it !
                    break;
                }
            }
        }

        // returns found element or null
        return element;
    }
}

Related

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