Is there an alternative to multiple whiles loops?


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

            Iterator<Element> itrNome = elemPessoa.elementIterator("nome");

            while (itrNome.hasNext()) { 
                Element elemNome = (Element);

            Iterator<Element> itrEmail = elemPessoa.elementIterator("email");

            while (itrEmail.hasNext()) { 
                Element elemEmail = (Element);

            Iterator<Element> itrCelular = elemPessoa.elementIterator("celular");

            while (itrCelular.hasNext()) { 
                Element elemCelular = (Element);

        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"?>
      <nome>Marcielli teste</nome>
      <email>[email protected]</email>
      <email>[email protected]</email>


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 .

asked by anonymous 10.09.2016 / 23:25

1 answer


All that exists a certain standard is possible to abstract and make the generic code. So you can create a method that makes this code a generic "filling in the gaps" that are specialized. Example (not necessarily the best):

private void FillElements(Node no, String nomeNo, String valor) {
    Element elemPessoa = (Element)no;
    Iterator<Element> iterador = elemPessoa.elementIterator(nomeNo);
    while (iterador.hasNext()) { 
        Element elemento = (Element);


FillElements(no, "idpessoa", String.valueOf(idPessoa)) //preenche as lacunas
FillElements(no, "nome", nome)
FillElements(no, "email", email)
FillElements(no, "celular", celular)

I'm not getting into the merit if the code is correct and does the desired or is well written and could be better, even by not knowing the full context, I'm just showing how to generalize the posted code and avoid repetition. >

This can be considered DRY .

10.09.2016 / 23:44