The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > org.w3c.dom  [30 examples] > Adding and Removing Nodes  [6 examples]

e541. Adding a Comment to a DOM Document

When creating a comment node, the string `--' must never appear in the comment text. The default XML writers in J2SE 1.4 will output the comment text with the `--' and therefore generate invalid XML.
    // Obtain an XML document; this method is implemented in
    // e510 The Quintessential Program to Create a DOM Document from an XML File
    Document doc = parseXmlFile("infilename.xml", false);
    
    // 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);
    
    // Find all elements with the name "entry" and append a comment
    NodeList list = doc.getElementsByTagName("entry");
    for (int i=0; i<list.getLength(); i++) {
        element = (Element)list.item(i);
        comment = doc.createComment("index="+i);
    
        // Add the comment after this element
        element.getParentNode().insertBefore(comment, element.getNextSibling());
    }
    
    // "--" must never appear in the text used to create the comment
    comment = doc.createComment("invalid -- comment");
    boolean validComment = comment.getNodeValue().indexOf("--") < 0;
This is the sample input for the example:
    <?xml version="1.0" encoding="UTF-8"?>
    <map>
        <entry key="key1" value="value1" />
        <entry key="key2" />
    </map>
The resulting XML from running the example is:
    <?xml version="1.0" encoding="UTF-8"?>
    <!--A Document Comment--><map>
        <entry key="key1" value="value1"/><!--index=0-->
        <entry key="key2"/><!--index=1-->
    </map>

 Related Examples
e539. Adding a Node to a DOM Document
e540. Adding a CDATA Section to a DOM Document
e542. Adding a Processing Instruction to a DOM Document
e543. Adding a Text Node to a DOM Document
e544. Removing a Node from a DOM Document

See also: Element Attributes    Elements    Getting Nodes    Text Nodes    XPath   


© 2002 Addison-Wesley.