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

Asked

Viewed 174 times

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>

1 answer

0


Create a class Contato that will serve as a model:

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 your 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 which 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.