Attempts to find a leading comment above this node until either a Comment is encountered or another Element is found instead. - Java XML

Java examples for XML:XML Node Operation

Description

Attempts to find a leading comment above this node until either a Comment is encountered or another Element is found instead.

Demo Code


//package com.java2s;

import org.w3c.dom.Comment;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class Main {
    /**//from  w ww. j ava 2s.  c om
     * Attempts to find a leading comment above this node until either a Comment
     * is encountered or another Element is found instead.
     *
     * @param node
     *            The node to search for a leading comment to.
     * @return A leading comment or null.
     */
    public static Comment findLeadingComment(Node node) {
        Node leadingNode = node.getPreviousSibling();
        while (leadingNode != null && !(leadingNode instanceof Element)
                && !(leadingNode instanceof Comment))
            leadingNode = leadingNode.getPreviousSibling();
        if (leadingNode != null && leadingNode instanceof Comment)
            return (Comment) leadingNode;
        return null;
    }
}

Related Tutorials