1

here is my code:

Element FICHADAS = new Element("FICHADAS");
Document doc = new Document(FICHADAS);
try{

    Element fichada = new Element("fichada");
    //Nº TERMINAL
    fichada.addContent(new Element("N_Terminal").setText(props.getProperty("N_TERMINAL")));
    //TARJETA
    fichada.addContent(new Element("Tarjeta").setText(codOperario));
    //FECHA
    Date fechaFormatoFecha = new Date( );
    fichada.addContent(new Element("Fecha").setText(formatoFecha.format(fechaFormatoFecha)));
    //HORA
    Date fechaFormatoHora = new Date( );
    fichada.addContent(new Element("Hora").setText(formatoHora.format(fechaFormatoHora)));
    //CAUSA
    fichada.addContent(new Element("Causa").setText("2"));
    doc.getRootElement().addContent(fichada);
    XMLOutputter xmlOutput = new XMLOutputter();
    xmlOutput.setFormat(Format.getPrettyFormat());
    xmlOutput.output(doc, new FileWriter("fichadas.xml"));

} catch(IOException io){
}

I'm creating a new document each time that i execute the program and i only want to create it if isn't exists, if the document exists just add the content.

Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
marcss
  • 253
  • 2
  • 14

2 Answers2

4

I think this is what you want to do. Just given a pseudo code:

File f = new File("fichadas.xml");
if(f.exists()){
//open file and write in it
} 
else{
//create new file
}
Madhusudan
  • 4,637
  • 12
  • 55
  • 86
3

Look at this constructor of Filewriter

Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.

Also FIRST you must check if file exists:

File fichadas=new File("fichadas.xml");
if (fichadas.exists()){
     // append
     xmlOutput.output(doc, new FileWriter("fichadas.xml", true));
} else {
     // create 
     xmlOutput.output(doc, new FileWriter("fichadas.xml"));
}

UPDATE to avoid the declaration, you must use Format.setOmitDeclaration(boolean). So you must add a format to the XMLOutputter:

// declare XMLOutputter 
XMLOutputter xmlOutput = new XMLOutputter();

// declare Format
Format fmt = Format.getPrettyFormat();

// set omit declaration to true
fmt.setOmitDeclaration(true);

// assign Format to XMLOutputter 
xmlOutput.setFormat(fmt);
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
  • thanks, now is adding the content but every time that i execute it adds this line: and the root tag in this case FICHADAS – marcss Apr 24 '15 at 08:48
  • now showed me that error: Multiple markers at this line - File cannot be resolved to a type – marcss Apr 24 '15 at 08:53
  • 1
    organize your imports or change `File` for `java.io.File` – Jordi Castilla Apr 24 '15 at 08:55
  • imports problem solved, but i have the same line () in the xml every time that i executed the code – marcss Apr 24 '15 at 08:59
  • 1
    I found that JDOM has this public boolean getOmitDeclaration() Returns whether the XML declaration will be omitted., how can i use it? – marcss Apr 24 '15 at 09:17