java JDOM xml file read and update



i just need to check weather the file have a root node(if not it means its newly created using Createnewfile() method) and if it isn't make one and append some info to the xml file but when i run this its says premature end of file exception please i'm new to java and do not understand what it is. and im also running this on netbeans



private void writexml(String task1,String date1,String detail1)
{
try {
SAXBuilder builder = new SAXBuilder();

Document doc = (Document) builder.build(new File("task.xml"));


if(!doc.hasRootElement()){

Element theroot = new Element("task");
doc.setRootElement(theroot);

}
Element root = doc.getRootElement();
Element task= new Element(task1);
Element date=new Element("dates");
date.addContent(date1);
Element detail = new Element("details");
detail.addContent(detail1);
task.addContent(date);
task.addContent(detail);
root.addContent(task);


XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
xout.output(doc, new FileWriter("task.xml"));

JOptionPane.showMessageDialog(null,"Saved");

} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}

No comments:

Post a Comment