Example usage for org.w3c.dom Comment getParentNode

List of usage examples for org.w3c.dom Comment getParentNode

Introduction

In this page you can find the example usage for org.w3c.dom Comment getParentNode.

Prototype

public Node getParentNode();

Source Link

Document

The parent of this node.

Usage

From source file:DOMUtil.java

/**
 * Automatically set text in a Node. Basically we find the first
 * Text node beneath the current node and replace it with a
 * CDATASection for the incoming text. All other Text nodes are
 * removed. Throws a DOMException if it's illegal to add a Text
 * child to the particular node.//from   www .j  a  va 2s  . c  o  m
 *
 * @param node the starting node for the search.
 * @param text the text to be set
 * @param allowMarkupInText whether to allow markup in text to pass through unparsed
 * @return the updated node
 * @throws DOMException if the Text object is not found
 */
public static Node setTextInNode(Node node, String text, boolean allowMarkupInText) {
    //start by setting the value in the first text node we find with a comment
    Comment comment = node.getOwnerDocument().createComment("");
    Node newNode = null;

    //csc_092701.1 - support both encoded/unencoded text
    if (allowMarkupInText)
        newNode = node.getOwnerDocument().createCDATASection(text);
    else
        newNode = node.getOwnerDocument().createTextNode(text);
    //System.out.println ("newNode: "+newNode);

    Text textComp = DOMUtil.findFirstText((Element) node);
    //System.out.println ("textComp:"+textComp);        
    if (textComp == null) {
        node.appendChild(comment);
    } else {
        Node parent = textComp.getParentNode();
        parent.replaceChild(comment, textComp);
    }

    //now remove all the rest of the text nodes
    removeAllTextNodes(node);

    //now replace the comment with the newNode
    Node parent = comment.getParentNode();
    parent.replaceChild(newNode, comment);
    //System.out.println ("parent:  "+parent);        
    //System.out.println ("result:  "+DOMUtil.findFirstText((Element) parent));        
    //DOMUtil.printStackTrace(parent.getOwnerDocument().getDocumentElement());
    return node;
}