Java examples for XML:XML Node
Count the DOM element nodes before the supplied node, having the specified tag name, not including the node itself.
// This library is free software; you can redistribute it and/or //package com.java2s; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /**// w ww .ja v a 2s. com * 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; } }