First you have to read the file before adding the new comments:
private static Document lerArquivo(String path) throws FileNotFoundException, JDOMException, IOException{
Document doc = null;
Element raiz = null;
File xmlFile = new File(path);
if(xmlFile.exists()) {
//ler arquivo se encontrado
FileInputStream fis = new FileInputStream(xmlFile);
SAXBuilder sb = new SAXBuilder();
doc = sb.build(fis);
fis.close();
} else {
//cria arquivo se não existir
doc = new Document();
raiz = new Element("comentarios");
}
return doc;
}
Then you have to use the root element to add new comments:
final String PATH = "C:\\xml.xml";
Document myDocument = lerArquivo(PATH);
Element comentarios = myDocument.getRootElement();
Element comentario = new Element("comentario");
The complete example:
import java.io.*;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.XMLOutputter;
public class JDOMExemplo{
final String PATH="C:\\xml.xml";
public static void main(String[] args) throws Exception {
Document myDocument = lerArquivo(PATH);
Element comentarios = myDocument.getRootElement();
Element comentario = new Element("comentario");
comentario.setAttribute("id", "123");
Element nome = new Element("nome");
nome.setText("Otavio");
Element tempo = new Element("tempo");
tempo.setText("0.00");
Element conteudo = new Element("conteudo");
conteudo.setText("Teste de Comentário");
comentario.addContent(nome);
comentario.addContent(tempo);
comentario.addContent(conteudo);
comentarios.addContent(comentario);
XMLOutputter xout = new XMLOutputter();
try {
xout.output(myDocument, System.out);
} catch (IOException e) {
e.printStackTrace();
}
try {
FileWriter arquivo = new FileWriter(new File(PATH));
xout.output(myDocument, arquivo);
} catch (IOException e) {
e.printStackTrace();
}
}
private static Document lerArquivo(String path) throws FileNotFoundException, JDOMException, IOException{
Document doc = null;
Element raiz = null;
File xmlFile = new File(path);
if(xmlFile.exists()) {
// try to load document from xml file if it exist
// create a file input stream
FileInputStream fis = new FileInputStream(xmlFile);
SAXBuilder sb = new SAXBuilder();
doc = sb.build(fis);
raiz = doc.getRootElement();
fis.close();
} else {
// if it does not exist create a new document and new root
doc = new Document();
raiz = new Element("comentarios");
}
return doc;
}
}
Thanks man, exactly what I needed
– Otavio Souza Rocha