Insert a CDATASection Node in Java

Description

The following code shows how to insert a CDATASection Node.

Example


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
/*from   w ww  .  j  ava 2s.co m*/
import org.w3c.dom.CDATASection;
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);

      addCDATA(doc);

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


  public static void addCDATA(Document doc) {
    Element root = doc.getDocumentElement();
    Element place = (Element)root.getFirstChild();
    Element directions = (Element)place.getLastChild();
    String dirtext = "cdData.";
    CDATASection dirdata = doc.createCDATASection(dirtext);
    directions.replaceChild(dirdata,directions.getFirstChild());
  }
}


<locations>
    <place>
        <name>name</name>
        <directions>direction</directions>
    </place>
</locations>
       
   ]]>
</code>
<result><![CDATA[    
  <?xml version="1.0" standalone="yes"?>
<locations>
    <place>
        <name>
            oldName
        </name>
        <directions>

        </directions>
    </place>
</locations>




















Home »
  Java Tutorial »
    XML »




DOM
SAX