Get XML Element that has attribute id="xyz". - Java XML

Java examples for XML:XML Attribute

Description

Get XML Element that has attribute id="xyz".

Demo Code

/*/*ww  w  .jav  a  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/>.
 */
//package com.java2s;
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 Tutorials