Java XML Node Previous countElementsBefore(Node node, String tagName)

Here you can find the source of countElementsBefore(Node node, String tagName)

Description

Count the DOM element nodes before the supplied node, having the specified tag name, not including the node itself.

License

Open Source License

Parameter

Parameter Description
node Node whose element siblings are to be counted.
tagName The tag name of the sibling elements to be counted.

Return

The number of siblings elements before the supplied node with the specified tag name.

Declaration

public static int countElementsBefore(Node node, String tagName) 

Method Source Code

//package com.java2s;
// License as published by the Free Software Foundation; either

import org.w3c.dom.Element;

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

public class Main {
    /**/*w  w  w  .  ja  va 2 s.  c  om*/
     * Count the DOM element nodes before the supplied node, having the specified
     * tag name, not including the node itself.
     * <p/>
     * Counts the sibling nodes.
     *
     * @param node    Node whose element siblings are to be counted.
     * @param tagName The tag name of the sibling elements to be counted.
     * @return The number of siblings elements before the supplied node with the
     *         specified tag name.
     */
    public static int countElementsBefore(Node node, String tagName) {
        Node parent = node.getParentNode();

        NodeList siblings = parent.getChildNodes();
        int count = 0;
        int siblingCount = siblings.getLength();

        for (int i = 0; i < siblingCount; i++) {
            Node sibling = siblings.item(i);

            if (sibling == node) {
                break;
            }
            if (sibling.getNodeType() == Node.ELEMENT_NODE && ((Element) sibling).getTagName().equals(tagName)) {
                count++;
            }
        }

        return count;
    }
}

Related

  1. countElementsBefore(Node node, String tagName)
  2. getAncesters(Node node)
  3. getAncestor(Node node, String ancestorName)
  4. getAncestorNode(Node visualNode, String tagName)