Insert Comment to a DOM in Java

Description

The following code shows how to insert Comment to a DOM.

Example


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
//w w w  .java2 s  .co m
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

public class Main {
  static public void main(String[] arg) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringElementContentWhitespace(true);

    Document doc = null;
    try {
      DocumentBuilder builder = dbf.newDocumentBuilder();
      InputSource is = new InputSource("personWithDTD.xml");
      doc = builder.parse(is);

      addComment(doc);

    } catch (Exception e) {
      System.err.println(e);
    }
  }

  public static void addComment(Document doc) {
    Element root = doc.getDocumentElement();
    Element folks = (Element)root.getLastChild();
    Comment comment = doc.createComment("Text of the comment");
    root.insertBefore(comment,folks);
  }

}


<locations>
    <place>
        <name>oldName</name>
        <directions>oldDirection</directions>
    </place>
</locations>
       
   ]]>
</code>
<result><![CDATA[    
  <?xml version="1.0" standalone="yes"?>
<locations>
    <!-- Text of the comment -->
    <place>
        <name>
            oldName
        </name>
        <directions>
            oldDirection
        </directions>
    </place>
</locations>




















Home »
  Java Tutorial »
    XML »




DOM
SAX