Java 怎么在所提供的节点之前计算所提供类型(nodeType)的DOM节点,不包括节点本身

2019年7月24日22:43:58Java 怎么在所提供的节点之前计算所提供类型(nodeType)的DOM节点,不包括节点本身已关闭评论 323 933字阅读3分6秒

1.简介

Java 怎么在所提供的节点之前计算所提供类型(nodeType)的DOM节点,不包括节点本身?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

 

import org.w3c.dom.*;

public class Main {
    
    public static int countNodesBefore(Node node, short nodeType) {
        Node parent = node.getParentNode();
        if (parent == null) {
            System.out.println("Cannot count nodes before [" + node
                    + "]. [" + node + "] has no parent.");
            return 0;
        }

        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() == nodeType) {
                count++;
            }
        }

        return count;
    }

    
    public static int countNodesBefore(Node node) {
        Node parent = node.getParentNode();
        if (parent == null) {
            System.out.println("Cannot count nodes before [" + node
                    + "]. [" + node + "] has no parent.");
            return 0;
        }

        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;
            }
            count++;
        }

        return count;
    }
}

 
继续阅读