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.

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

1 Answer 1

3

Remove this line:

doc.setRootElement(FICHADAS);

because you set the root element here:

Document doc = new Document(FICHADAS);
Sign up to request clarification or add additional context in comments.

2 Comments

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?
You have to escape the backslash: xmlOutput.output(doc, new FileWriter("C:\\file.xml"));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.