Search code examples
javaxmljdomjdom-2

create xml document and add or just add if document exixts


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.


Solution

  • 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);