Search code examples
javaxmljdomjdom-2

can not create the xml file using jdom


Here is my code:

import java.io.FileWriter; 
import java.io.IOException; 
import org.jdom2.Attribute; 
import org.jdom2.Document; 
import org.jdom2.Element; 
import org.jdom2.output.Format; 
import org.jdom2.output.XMLOutputter;


try {
    Element FICHADAS = new Element("FICHADAS");
    Document doc = new Document(FICHADAS);
    doc.setRootElement(FICHADAS);
    Element fichada = new Element("fichada");
    fichada.addContent(new Element("N_Terminal").setText("XX"));
    fichada.addContent(new Element("Tarjeta").setText("XX"));
    fichada.addContent(new Element("Fecha").setText("XX"));
    fichada.addContent(new Element("Hora").setText("XX"));
    fichada.addContent(new Element("Causa").setText("XX"));
    doc.getRootElement().addContent(fichada);
    XMLOutputter xmlOutput = new XMLOutputter();
    xmlOutput.setFormat(Format.getPrettyFormat());
    xmlOutput.output(doc, new FileWriter("c:\file.xml"));
} catch(IOException e) {

}

i try to find the file.xml in C:\ but is not here and I don't know why, and the console show me that: The element "FICHADAS" could not be added as the root of the document: The Content already has an existing parent document

//NEW I was thinking, and now i only need to add the new fichadas to the existing document, not need to create it every time that i opened the program.


Solution

  • Remove this line:

    doc.setRootElement(FICHADAS);
    

    because you set the root element here:

    Document doc = new Document(FICHADAS);