
Hi
Can anyone help me how to read and write an xml file which has CData using java

Hi Friend,
Try the following code:
1) CreateCDATA.java:
import java.io.*;
import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;
public class CreateCDATA {
public static void main(String[] args) {
String xml =
"<root>" +
" <messages>" +
" <message></message>" +
" </messages>" +
"</root>";
SAXBuilder builder = new SAXBuilder();
try {
Document document = builder.build(new StringReader(xml));
Element root = document.getRootElement();
Element comments = root.getChild("messages");
Element comment = comments.getChild("message");
comment.setContent(new CDATA("Hello World"));
Writer writer=new FileWriter(new File("new.xml"));
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
outputter.output(document, writer);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
2)ReadCDATA.java:
import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
public class ReadCDATA {
public static void main(String[] args) throws Exception {
File file = new File("new.xml");
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(file);
NodeList nodes = doc.getElementsByTagName("messages");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList title = element.getElementsByTagName("message");
Element line = (Element) title.item(0);
System.out.println("Message: " + getCharacterDataFromElement(line));
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
}
Thanks

how to read a xml file(login file with username and password)verify it and if it is correct pass the control to home page.
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.