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]

e543. Adding a Text Node to a DOM Document

If any special characters appear in the text of a text node (e.g., <>"), they are automatically converted to entities by the XML writers.
    // 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 CDATA section to the root element
    Element element = doc.getDocumentElement();
    Text text = doc.createTextNode("data\n");
    element.appendChild(text);
    
    // Special characters are automatically converted to entities by the XML writers
    text = doc.createTextNode("<>&\"'");
    element.appendChild(text);
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"?>
    <map>
        <entry key="key1" value="value1"/>
        <entry key="key2"/>
    data
    &lt;&gt;&amp;"'</map>

 Related Examples
e539. Adding a Node to a DOM Document
e540. Adding a CDATA Section to a DOM Document
e541. Adding a Comment to a DOM Document
e542. Adding a Processing Instruction 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.