Java XML Node Sibiling getPreviousSibling(Node node, short nodeType)

Here you can find the source of getPreviousSibling(Node node, short nodeType)

Description

get Previous Sibling

License

Open Source License

Declaration

public static Node getPreviousSibling(Node node, short nodeType) 

Method Source Code


//package com.java2s;
/*/* w  ww  . j a  va  2s  .com*/
 * ePUB Corrector - https://github.com/vysokyj/epub-corrector/
 *
 * Copyright (C) 2012 Jiri Vysoky
 *
 * ePUB Corrector is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * by the Free Software Foundation; either version 3 of the License,
 * or (at your option) any later version.
 *
 * ePUB Corrector 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
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Cobertura; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA
 */

import org.w3c.dom.*;

public class Main {
    public static Node getPreviousSibling(Node node, short nodeType) {
        Node parent = node.getParentNode();
        if (parent == null) {
            System.out.println("Cannot get node [" + node + "] previous sibling. [" + node + "] has no parent.");
            return null;
        }

        NodeList siblings = parent.getChildNodes();
        int siblingCount = siblings.getLength();
        int nodeIndex = 0;

        // Locate the node
        for (int i = 0; i < siblingCount; i++) {
            Node sibling = siblings.item(i);

            if (sibling == node) {
                nodeIndex = i;
                break;
            }
        }

        if (nodeIndex == 0) {
            return null;
        }

        // Wind back to sibling
        for (int i = nodeIndex - 1; i >= 0; i--) {
            Node sibling = siblings.item(i);

            if (sibling.getNodeType() == nodeType) {
                return sibling;
            }
        }

        return null;
    }
}

Related

  1. getNextSiblingElementByName(Node node, String name)
  2. getNextSiblingElementNS(Node node, String uri)
  3. getNextSiblingElementNS(Node node, String[][] elemNames)
  4. getNextVisibleSiblingElement(Node node)
  5. getPreHomoSibling(Node aNode)
  6. getPreviousSiblingByName(Node currentNode, String tagName)
  7. getPreviousSiblingElement(Node node)
  8. getPreviousSiblingElement(Node node)
  9. getSibling(Node current)