quarta-feira, 24 de outubro de 2007

Como criar e ler um XML

Tem que baixar o .jar http://xstream.codehaus.org

public class Exportar
{

@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception
{
Aluno aluno1 = new Aluno(1L, "Joao da Penha", new Date());
Aluno aluno2 = new Aluno(2L, "Maria Joao", new Date());

Collection alunos = new ArrayList();
alunos.add(aluno1);
alunos.add(aluno2);

//Criando um xml
String encoding = "ISO-8859-1";
XStream stream = new XStream(new DomDriver(encoding));
stream.alias("aluno", Aluno.class);

File xmlFile = new File("C:\\aluno.xml");

String xmlFileContent = new String("\r\n".getBytes(), encoding);
xmlFileContent += stream.toXML(alunos);

System.out.println("########### PRONTO TA CRIADO O XML #############");
System.out.println(xmlFileContent);

FileWriter fileWriter = new FileWriter(xmlFile);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(xmlFileContent);

bufferedWriter.flush();
bufferedWriter.close();

//Lendo um xml
Collection alunosInput = new ArrayList();

BufferedReader inputXml = new BufferedReader(new FileReader("C:\\aluno.xml"));
alunosInput = (Collection) stream.fromXML(inputXml);
inputXml.close();


System.out.println("########### PRONTO TA CRIADO O OBJETO #############");

for (Aluno aluno : alunosInput)
{
System.out.println(aluno.getId());
System.out.println(aluno.getNome());
System.out.println(aluno.getNascimento());
}
}
}

Aluno.class

public class Aluno
{
public Aluno()
{
super();
}

public Aluno(Long id, String nome, Date nascimento)
{
super();
this.id = id;
this.nome = nome;
this.nascimento = nascimento;
}

private Long id;
private String nome;
private Date nascimento;

public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getNascimento() {
return nascimento;
}
public void setNascimento(Date nascimento) {
this.nascimento = nascimento;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
}

3 comentários:

Anônimo disse...

Olá, sou leigo em java e estou aprendendo a usá-lo.

Baixei o arquivo .jar citado, mas o q faço com ele ?

Braian disse...

Parabéns pelo post e pelo blog. Gostei, bem explicativo!!!

Braian disse...

Só "editando", pra melhorar, merecia uma formatação meio "CODE" aí nos códigos. Ficava mais legal e organizado.

Valeu!!!