Java XML Node Find findNodeIndex(Node node)

Here you can find the source of findNodeIndex(Node node)

Description

find Node Index

License

EUPL

Declaration

private static int findNodeIndex(Node node) 

Method Source Code

//package com.java2s;
/*//w  ww. j  av  a 2s  .c  om
 * Copyright 2004-2014 SmartBear Software
 *
 * Licensed under the EUPL, Version 1.1 or - as soon as they will be approved by the European Commission - subsequent
 * versions of the EUPL (the "Licence");
 * You may not use this work except in compliance with the Licence.
 * You may obtain a copy of the Licence at:
 *
 * http://ec.europa.eu/idabc/eupl
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the Licence is
 * distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the Licence for the specific language governing permissions and limitations
 * under the Licence.
*/

import org.w3c.dom.Node;

public class Main {
    private static int findNodeIndex(Node node) {
        String nm = node.getLocalName();
        String ns = node.getNamespaceURI();
        short nt = node.getNodeType();

        Node parentNode = node.getParentNode();
        if (parentNode.getNodeType() != Node.ELEMENT_NODE) {
            return 1;
        }

        Node child = parentNode.getFirstChild();

        int ix = 0;
        while (child != null) {
            if (child == node) {
                return ix + 1;
            }

            if (child.getNodeType() == nt && nm.equals(child.getLocalName())
                    && ((ns == null && child.getNamespaceURI() == null)
                            || (ns != null && ns.equals(child.getNamespaceURI())))) {
                ix++;
            }

            child = child.getNextSibling();
        }

        throw new RuntimeException("Child node not found in parent!?");
    }
}

Related

  1. findNodeByAttribute(Document document, String tagName, String attributeName, String attributeValue)
  2. findNodeByName(Document doc, String pathExpression)
  3. findNodeByTagName(Document document, String tagName)
  4. findNodeByXpath(org.w3c.dom.Document doc, String xpathEx)
  5. findNodeIndex(Node node)
  6. findNodeLong(Node node)
  7. findNodesByTagName(Document document, String tagName)
  8. findNodesNamed(Node node, String lookForName, Collection ret)
  9. findNodeValue(Node aNode, String aName)