JDOM CDATA Example, How to add CDATA section in xml document.


 

JDOM CDATA Example, How to add CDATA section in xml document.

In this tutorial, you will see how to add CDATA section in xml document.

In this tutorial, you will see how to add CDATA section in xml document.

JDOM CDATA Example, How to add CDATA section in xml document.

In this tutorial, we will see how to add CDATA section in xml document. In xml document, CDATA section is a part of element content that is like as character data. Text inside this section will be ignored by the parser.

In this example, we can create a CDATA node with the help CDATA class.

The CDATA(java.lang.String string) constructor of CDATA class crates a CDATA new node with a string.

The setContent(Content content ) and addContent(Content content) method of Element class is used to set and add  the content at element.

Code:

company.xml

<?xml version="1.0" encoding="UTF-8"?>
<Company>
   <Employee >            
        <name>xyz</name>
        <Detail></Detail>              
           <Phoneno>0808</Phoneno> 
           <CompanyName>RoseIndia.net</CompanyName>       
      </Employee>  
</Company>

CdataSection.java

package roseindia;
import java.io.File;
import org.jdom.CDATA;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class CdataSection {
   public static void main(String[] args) {
  String xml ="Company.xml";
  File  file=new File(xml);   
  SAXBuilder builder = new SAXBuilder();
  try {
   Document doc = builder.build(file);
   Element rootElement = doc.getRootElement();
   Element empElement = rootElement.getChild("Employee");
   Element detailElement = empElement.getChild("Detail");
   CDATA cdata=new CDATA("<info>Working in RoseIndia.</info>.");
   CDATA cdata2= new CDATA("<work>Programmer</work>.");
      detailElement.setContent(cdata);
      detailElement.addContent(cdata2);   
   XMLOutputter outXML = new XMLOutputter(Format.getPrettyFormat());
      outXML.output(doc, System.out);   
      String charData = detailElement.getText();
      System.out.println("Charater data : " + charData);
       catch (Exception ex {
            System.out.println("Exception : "+ex); }
      }
}
Output:
<?xml version="1.0" encoding="UTF-8"?>
<Company>
<Employee>
<name>xyz</name>
<Detail><![CDATA[<info>Working in RoseIndia.</info>.]]><![CDATA[<work>Programmer</work>.]]> </Detail>
<Phoneno>0808</Phoneno>
<CompanyName>RoseIndia.net</CompanyName>
</Employee>
</Company>
Charater data : <info>Working in RoseIndia.</info>.<work>Programmer</work>.

Download this code

Ads