Here you can find the source of getOccurs(String nodeName, NodeList nodes)
Parameter | Description |
---|---|
nodeName | The name of the node whose occurrences are requested |
nodes | The list of nodes that will be searched for occurrences of nodeName. |
public static int getOccurs(String nodeName, NodeList nodes)
//package com.java2s; //License from project: Open Source License import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /**/*w w w. j ava 2s.c om*/ * Returns the occurrences of a given node (specified by its name) * in a given list of nodes. Counts all subsequent occurs after the * first one. * * @param nodeName The name of the node whose occurrences are requested * @param nodes The list of nodes that will be searched for occurrences of * nodeName. * @return The number of the first subsequent occurences of nodeName. * Greater than or equal to 0. */ public static int getOccurs(String nodeName, NodeList nodes) { int occurs = 0; int childNr = 0; boolean foundFirstOccurence = false; while (childNr < nodes.getLength()) { Node node = nodes.item(childNr); if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeName().compareTo(nodeName) == 0) { occurs++; foundFirstOccurence = true; } else { if (foundFirstOccurence) { return occurs; } } } childNr++; } return occurs; } /** * Returns the occurrences of a given node/element. Checks whether the previous/following * elements have the same name. * * @param node The node whose occurrences should be determined. * @return The occurrences of node. Greater than or equal to 1. */ public static int getOccurs(Node node) { int occurs = 1; String nodeName = node.getNodeName(); Node prevSib = node.getPreviousSibling(); while (prevSib != null) { if (prevSib.getNodeName().compareTo(nodeName) == 0 && prevSib.getNodeType() == Node.ELEMENT_NODE) { occurs++; prevSib = prevSib.getPreviousSibling(); } else { prevSib = null; } } Node nextSib = node.getNextSibling(); while (nextSib != null) { if (nextSib.getNodeName().compareTo(nodeName) == 0 && nextSib.getNodeType() == Node.ELEMENT_NODE) { occurs++; nextSib = nextSib.getNextSibling(); } else { nextSib = null; } } return occurs; } }