Java XML Element Get by ID getElementById(Document document, String id)

Here you can find the source of getElementById(Document document, String id)

Description

get Element By Id

License

Open Source License

Declaration

public static Element getElementById(Document document, String id) 

Method Source Code


//package com.java2s;
/*//  w  w  w.j  ava 2s. c om
 * 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. getElemenById(Document document, String elementId)
  2. getElementById(Document doc, String id, Map idMap)
  3. getElementById(Document dom, String id)
  4. getElementById(Document dom, String id, String localElementName)