Adding a Comment to a DOM Document - Java XML

Java examples for XML:XML Comment

Description

Adding a Comment to a DOM Document

Demo Code


import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class Main {
  public static void main(String[] args) {
    Document doc = null;//from   w w  w.  java2s .  c  om

    // Add a comment at the beginning of the document
    Element element = doc.getDocumentElement();
    Comment comment = doc.createComment("A Document Comment");
    element.getParentNode().insertBefore(comment, element);

    NodeList list = doc.getElementsByTagName("entry");
    for (int i = 0; i < list.getLength(); i++) {
      element = (Element) list.item(i);
      comment = doc.createComment("index=" + i);
      element.getParentNode().insertBefore(comment, element.getNextSibling());
    }

    comment = doc.createComment("comment");
    boolean validComment = comment.getNodeValue().indexOf("--") < 0;
  }
}

Related Tutorials