Estou precisando gerar um arquivo XML onde ele irá ler uma tabela no banco de dados e dentro do laço while ir pegando os dados da tabela e jogando para o XML conforme o código abaixo:
public static void geraXML() throws ParserConfigurationException, FileNotFoundException, IOException, ClassNotFoundException, SQLException,
TransformerConfigurationException, TransformerException{
fabrica = DocumentBuilderFactory.newInstance();
builder = fabrica.newDocumentBuilder();
documento = builder.newDocument();
getGerar(documento, "D:\");
}
public static void getGerar(Document doc, String path) throws FileNotFoundException, IOException, ClassNotFoundException, SQLException,
TransformerConfigurationException, TransformerException{
Conexao conexao = new Conexao("porta", "banco", "user", "senha", "host");
conexao.abrirConexao();
conexao.setSelect("select * from tabela_teste_n");
conexao.preparaSelect();
rs = conexao.resultSet();
Element start = doc.createElement("start");
start.setAttribute("versao", "6.0");
start.setAttribute("attrib", "EX01H58");
Element nome = doc.createElement("nome");
Element prof = doc.createElement("prof");
while(rs.next()){
nome.setTextContent(rs.getString("nome"));
prof.setTextContent(rs.getString("prof"));
start.appendChild(nome);
start.appendChild(prof);
}
doc.appendChild(start);
Transformer tran = TransformerFactory.newInstance().newTransformer();
tran.setOutputProperty(OutputKeys.INDENT, "yes");
Result out = new StreamResult(path + "/" + "testeXML.xml");
tran.transform(new DOMSource(doc), out);
conexao.fecharBanco();
}
O meu problema é que estou tentando dentro do laço while ir replicando as tag´s nome e prof com seus respectivos valores, porém no arquivo XML gerado só aparece o último valor e não a lista completa de valores.
O arquivo XML gerado fica desse jeito:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<start attrib="EX01H58" versao="6.0">
<nome>João</nome>
<prof>x2xx52x015850</prof>
</start>
E na verdade deveria ficar assim:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<start attrib="EX01H58" versao="6.0">
<nome>João</nome>
<prof>x2xx52x015850</prof>
<nome>José</nome>
<prof>x2zz552x015850</prof>
<nome>Mané</nome>
<prof>x2xx8015850</prof>
</start>
Alguém tem alguma dica para eu corrigir esse laço?