Java XML NodeList getElementById(NodeList nodeList, String id)

Here you can find the source of getElementById(NodeList nodeList, String id)

Description

Get Element that has attribute id="xyz".

License

Open Source License

Declaration

public static Element getElementById(NodeList nodeList, String id) 

Method Source Code


//package com.java2s;
/*/*from w  w w . j  a  v a 2  s .  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. getArray(NodeList nodeList)
  2. getContent(NodeList nl, String path)
  3. getCurrentListPosition(Node refNode, NodeList list)
  4. getDeepNode(String name[], NodeList nodes)
  5. getDSNameListInScriptText(String scriptText, NodeList tableList)
  6. getElementFromItem(NodeList list, int index)
  7. getElementFromNodeList(NodeList nl)
  8. getElementList(NodeList list)
  9. getElements(NodeList nodeList, String localname, String namespaceURI)