CDATASection
In this chapter you will learn:
Inserting a CDATASection Node
import java.io.StringReader;
import java.io.StringWriter;
//from j ava 2 s .com
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
public class Main {
public static void main(String[] args) throws Exception {
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlRecords));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(is);
Element root = doc.getDocumentElement();
Element last = (Element)root.getLastChild();
CDATASection dirdata = doc.createCDATASection("java2s.com");
root.insertBefore(dirdata,last);
toString(doc);
}
private static void toString(Document newDoc) throws Exception{
DOMSource domSource = new DOMSource(newDoc);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
StringWriter sw = new StringWriter();
StreamResult sr = new StreamResult(sw);
transformer.transform(domSource, sr);
System.out.println(sw.toString());
}
static String xmlRecords =
"<data>" +
" <employee>" +
" <name>Tom</name>"+
" <title>Manager</title>" +
" </employee>" +
" <employee>" +
" <name>Jerry</name>"+
" <title>Programmer</title>" +
" </employee>" +
"</data>";
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » XML