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