创建xml文档并添加或仅添加文档exixts

时间:2015-04-24 08:38:31

标签: java xml jdom jdom-2

这是我的代码:

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){
}

我每次执行程序时都会创建一个新文档,如果不存在,我只想创建它,如果文档存在则只添加内容。

2 个答案:

答案 0 :(得分:4)

我认为这就是你想要做的。刚给出一个伪代码:

File f = new File("fichadas.xml");
if(f.exists()){
//open file and write in it
} 
else{
//create new file
}

答案 1 :(得分:3)

请查看Filewriter

constructor
  

构造一个FileWriter对象,给定一个带有布尔值的文件名,指示是否附加写入的数据。

同样 FIRST 您必须检查文件是否存在:

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"));
}

更新以避免声明,您必须使用Format.setOmitDeclaration(boolean)。因此,您必须向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);