Java XML Node Find findElementById(Node head, String id)

Here you can find the source of findElementById(Node head, String id)

Description

Static method to find DOM elements by an ID field

License

Open Source License

Parameter

Parameter Description
head head of the DOM
id value to look for

Return

element that id was found in

Declaration

public static Element findElementById(Node head, String id) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

public class Main {
    /**//w w  w. j a v  a2s . c o  m
     * Static method to find DOM elements by an ID field
     * @param head head of the DOM
     * @param id value to look for
     * @return element that id was found in
     */
    public static Element findElementById(Node head, String id) {
        Element element = null;
        for (Node node = head.getFirstChild(); node != null; node = node.getNextSibling()) {
            if (node.hasChildNodes()) {
                element = findElementById(node, id);
                if (element != null)
                    return element;
            }
            if (node.hasAttributes()) { // only elements will have attributes
                NamedNodeMap attributes = node.getAttributes();
                for (int i = 0; i < attributes.getLength(); i++) {
                    //System.out.println("Node: "+node+ " "+id);
                    //System.out.println("attributes: "+i+" "+attributes.item(i)+" "+attributes.item(i).getTextContent());
                    if (attributes.item(i).getTextContent().equals(id)) {
                        element = (Element) node;
                        //System.out.println("found id");
                        break;
                    }
                }
            }
            if (element != null)
                break;
        }
        return element;
    }
}

Related

  1. findAllNodesRecursive(Node n, String name)
  2. findAllProcessingIstructions(Node node, String name, List result)
  3. findAllUrisRecursive(Node node, List nodes)
  4. findElement(Node node, String tagName)
  5. findElement(Node startNode, String name, String namespace)
  6. findElementById(Node node, String id)
  7. findElementByName(Node node, final String name)
  8. findElementByTag(Set nodes, String tag)
  9. findElementNodeByName(Node node, String name)