7
I have a method alterar() that change the data of a particular element of my XML Person, however, this routine uses several whiles one 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 Pessoa 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 any alternative to all of these whiles?
PS: I am using the dom4j library to process and read the XML file.
For example:
Iterator<Element> itrIdPessoa = elemPessoa.elementIterator("idpessoa");it returns here how many items? because eachnois an item of this XML?– novic
@Virgilionovic ai returns a theoretically, the
noin Sso can consider the tagpessoa.– gato
For me @Denercarvalho are unnecessary interactions I believe everything is there...
– novic