Java XML Element Get by ID getElemenById(Document document, String elementId)

Here you can find the source of getElemenById(Document document, String elementId)

Description

get Elemen By Id

License

Open Source License

Parameter

Parameter Description
document a parameter
elementId a parameter

Declaration

public static Element getElemenById(Document document, String elementId) 

Method Source Code

//package com.java2s;
/******************************************************************************* 
 * Copyright (c) 2007 Red Hat, Inc.//from w  ww  . j av a  2s .c  o m
 * Distributed under license by Red Hat, Inc. All rights reserved.
 * This program is made available under the terms of the
 * Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Red Hat, Inc. - initial API and implementation
 ******************************************************************************/

import org.w3c.dom.Document;
import org.w3c.dom.Element;

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

public class Main {
    final public static String ID_ATTRIBUTE = "id";

    /**
     * 
     * @param document
     * @param elementId
     * @return
     */
    public static Element getElemenById(Document document, String elementId) {

        Element element = document.getDocumentElement();

        NodeList children = element.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if ((child.getNodeType() == Node.ELEMENT_NODE)
                    && elementId.equals(((Element) child).getAttribute(ID_ATTRIBUTE)))
                return (Element) child;

        }

        return null;

    }
}

Related

  1. getElementById(Document doc, String id, Map idMap)
  2. getElementById(Document document, String id)
  3. getElementById(Document dom, String id)
  4. getElementById(Document dom, String id, String localElementName)