Search code examples
javaxmljdomjdom-2

How can i create a different xml tag using a counter?


Here is my code:

Element FICHADAS = new Element("FICHADAS");
Document doc = new Document(FICHADAS);
try {
  if (fichadaHecha == false) {
    Element fichada = new Element("fichada");
    fichada.setAttribute(newAttribute("id", Integer.toString(contador)));
    fichada.addContent(new Element("N_Terminal").setText("XX"));
    fichada.addContent(new Element("Tarjeta").setText(codOperario));
    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:\\fichadas.xml"));
    contador = contador + 1;
    fichadaHecha = true;
  }
} catch(IOException io) {
}

I want to use the counter called contador to put it the number in the name in line Element fichada = new Element("fichada" + counter); but I don't know how to do it. Thanks.


Solution

  • Element fichada = new Element("fichada" + contador );

    This means that each document you create will have a differently named first child element of the root element. Is this actually what you want? And if you do, then you'd probably want to do something to the file name that you are writing to as it seems you will be constantly over-writing it.