3

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.

marcss
  • 253
  • 2
  • 14
  • Can you add the `import` statements, so we can see which objects do you use? – Jens Apr 22 '15 at 07:41
  • no, how can I add the import statements?¿? – marcss Apr 22 '15 at 07:44
  • The `import` statement are the firrst lines of your code. why you can not add it? from wich package is `Element`, `Document`, `XMLOutputter ? – Jens Apr 22 '15 at 07:47
  • 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; – marcss Apr 22 '15 at 07:48

1 Answers1

3

Remove this line:

doc.setRootElement(FICHADAS);

because you set the root element here:

Document doc = new Document(FICHADAS);
Jens
  • 67,715
  • 15
  • 98
  • 113
  • Thanks mate! and the last question in this line: xmlOutput.output(doc, new FileWriter("C:\file.xml")); seems that the program can not take the path because the "rare" characters, how can i do it? – marcss Apr 22 '15 at 07:59
  • 1
    You have to escape the backslash: `xmlOutput.output(doc, new FileWriter("C:\\file.xml")); ` – Jens Apr 22 '15 at 08:02