How to read this XML and ignore the ID field using XStream

0

I need to read the XML below and ignore the ID field of all contacts

<contatos>
  <contato>
    <Id>1</Id>
    <Nome>Madeline Mullins</Nome>
    <Telefone>(22) 9689-2958</Telefone>
  </contato>
  <contato>
    <Id>2</Id>
    <Nome>Kameko Morse</Nome>
    <Telefone>(11) 7194-9730</Telefone>
  </contato>
<contatos>
    
asked by anonymous 21.10.2016 / 22:13

1 answer

0

Create a class Contato that will serve as a template:

package models;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;

public class Contato {       

    @XStreamAlias("Nome") 
    @XStreamAsAttribute
    private String nome;

    @XStreamAlias("Telefone") 
    @XStreamAsAttribute
    private String telefone;

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getTelefone() {
        return telefone;
    }

    public void setTelefone(String telefone) {
        this.telefone = telefone;
    }    
}

and another class Contatos which is its root of xml :

package models;

import com.thoughtworks.xstream.annotations.XStreamImplicit;
import java.util.List;

public class Contatos  {

    @XStreamImplicit(itemFieldName="contato")
    private List<Contato> contato;

    public List<Contato> getContato() {
        return contato;
    }

    public void setContato(List<Contato> contato) {
        this.contato = contato;
    }    
}

These two classes are using Annotations > that are your settings.

Finally the code to load the information:

 File file1 = new File("document.xml"); // passe o caminho (path)

 XStream xstream = new XStream(new DomDriver());
 xstream.alias("contato", Contato.class);
 xstream.alias("contatos", Contatos.class);
 xstream.processAnnotations(Contato.class);
 xstream.processAnnotations(Contatos.class);
 // essa configuração ignora dados que a reflexão não encontrar.
 xstream.ignoreUnknownElements();  

 Contatos c1 = (Contatos)xstream.fromXML(file1);

 for(Contato c3: c1.getContato())
 {     
    System.out.println(c3.getNome());
    System.out.println(c3.getTelefone());
    System.out.println("*******************");
 }

Working with the XStream library in Java

    
22.10.2016 / 02:30