Here you can find the source of countElementsBefore(Node node, String tagName)
Parameter | Description |
---|---|
node | Node whose element siblings are to be counted. |
tagName | The tag name of the sibling elements to be counted. |
public static int countElementsBefore(Node node, String tagName)
//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; } }