I have a alterar()
method that changes the data of a particular element of my XML Person, however, this routine uses several% s of% s for each element, see below the routine:
public void alterar() {
try {
Document doc = parse(arquivo);
List<Node> nos = doc.selectNodes("//pessoas/pessoa[idpessoa='" + String.valueOf(idPessoa) + "']");
for (Node no: nos) {
Element elemPessoa = (Element) no;
Iterator<Element> itrIdPessoa = elemPessoa.elementIterator("idpessoa");
while (itrIdPessoa.hasNext()) {
Element elemIdPessoa = (Element) itrIdPessoa.next();
elemIdPessoa.setText(String.valueOf(idPessoa));
}
Iterator<Element> itrNome = elemPessoa.elementIterator("nome");
while (itrNome.hasNext()) {
Element elemNome = (Element) itrNome.next();
elemNome.setText(nome);
}
Iterator<Element> itrEmail = elemPessoa.elementIterator("email");
while (itrEmail.hasNext()) {
Element elemEmail = (Element) itrEmail.next();
elemEmail.setText(email);
}
Iterator<Element> itrCelular = elemPessoa.elementIterator("celular");
while (itrCelular.hasNext()) {
Element elemCelular = (Element) itrCelular.next();
elemCelular.setText(celular);
}
}
escrever(doc, arquivo);
}
catch (DocumentException ex) {
throw new RuntimeException();
}
catch (IOException ex) {
throw new RuntimeException();
}
catch (NoClassDefFoundError ex) {
System.err.println("Erro: " + ex.getMessage());
}
}
This is the structure of the Person XML file:
<?xml version="1.0" encoding="UTF-8"?>
<pessoas>
<pessoa>
<idpessoa>2</idpessoa>
<nome>Marcielli teste</nome>
<email>[email protected]</email>
<celular>88888888</celular>
</pessoa>
<pessoa>
<idpessoa>3</idpessoa>
<nome>Ana</nome>
<email>[email protected]</email>
<celular>1233121</celular>
</pessoa>
</pessoas>
Doubt
I would like to know if possible, if there is an alternative to all these while
s?
PS: I'm using the dom4j library to process and read the XML file .