Java XML Element Get by ID getElementById(Document doc, String id, Map idMap)

Here you can find the source of getElementById(Document doc, String id, Map idMap)

Description

get Element By Id

License

LGPL

Declaration

static Node getElementById(Document doc, String id, Map<String, Node> idMap) 

Method Source Code

//package com.java2s;
//License from project: LGPL 

import java.util.Map;

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

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

public class Main {
    static Node getElementById(Document doc, String id, Map<String, Node> idMap) {
        if (!idMap.containsKey(id)) {
            registerIDs(doc, doc.getDocumentElement(), idMap);
        }//from w w w  . ja  va 2  s.  c  o  m
        return idMap.get(id);
    }

    private static void registerIDs(Document doc, Node node, Map<String, Node> idMap) {
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            if (node.getAttributes().getNamedItem("id") != null) {
                final String id = node.getAttributes().getNamedItem("id").getNodeValue();
                idMap.put(id, (Element) node);
            }
        }
        NodeList children = node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            registerIDs(doc, children.item(i), idMap);
        }

    }
}

Related

  1. getElemenById(Document document, String elementId)
  2. getElementById(Document document, String id)
  3. getElementById(Document dom, String id)
  4. getElementById(Document dom, String id, String localElementName)