Java XML Element Get getElementIndex(Element element)

Here you can find the source of getElementIndex(Element element)

Description

Returns the index of element in the list of all elements with the same name in its parent node.

License

Open Source License

Declaration

public static int getElementIndex(Element element) 

Method Source Code

//package com.java2s;
/*//  w  w  w .j  av  a 2s . c  o  m
 *  RapidMiner
 *
 *  Copyright (C) 2001-2014 by RapidMiner and the contributors
 *
 *  Complete list of developers available at our web site:
 *
 *       http://rapidminer.com
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see http://www.gnu.org/licenses/.
 */

import org.w3c.dom.Element;

import org.w3c.dom.Node;

public class Main {
    /**
     * Returns the index of element in the list of all elements with the same name in its parent node.
     * If element's parent node is null, this function returns 0.
     */
    public static int getElementIndex(Element element) {
        int index = 1;
        Node sibling = element;
        while ((sibling = sibling.getPreviousSibling()) != null) {
            if (sibling instanceof Element) {
                Element siblingElement = (Element) sibling;

                // check if element names and element namespaces match 
                if (element.getLocalName().equals(siblingElement.getLocalName())
                        && (element.getNamespaceURI() == null ? siblingElement.getNamespaceURI() == null
                                : element.getNamespaceURI().equals(siblingElement.getNamespaceURI()))) {
                    ++index;
                }
            }
        }
        return index;
    }
}

Related

  1. getElementContents(Element element, String elementName)
  2. getElementDescendant(Element elem, String ns_uri, String tagName)
  3. getElementForLine(Document document, int line)
  4. getElementId(Element element)
  5. getElementIndex(Element ele)
  6. getElementLanguage(Element elemNode, String defaultLangCode)
  7. getElementLanguage(Element elemNode, String defaultLangCode)
  8. getElementList(Document doc, String expression)
  9. getElementList(Element dataRoot, String name)