Download this library http://repo1.maven.org/maven2/com/thoughtworks/xstream/xstream/1.4.11.1/xstream-1.4.11.jar.
And add the jar to the project
public class ManipuladorXml {
public boolean gravarXml(List<Usuario>usuarios,String nome) {
XStream xstream = new XStream(new DomDriver());
String xml = xstream.toXML(usuarios);
try {
SalvarArquivo(nome,xml);
return true;
} catch (IOException ex) {
Logger.getLogger(ManipuladorXml.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
public void lerXml(String nome) throws FileNotFoundException {
XStream xstream = new XStream(new DomDriver());
@SuppressWarnings("unchecked")
List<Usuario> dados = (List<Usuario>) xstream.fromXML(new FileReader(nome+".xml"));
for (Usuario dado : dados) {
System.out.println(dado.getNome());
System.out.println(dado.getIdade());
}
}
private void SalvarArquivo(String nome,String xml) throws IOException {
FileWriter arq = new FileWriter(nome + ".xml");
PrintWriter gravarArq = new PrintWriter(arq);
gravarArq.printf(xml);
arq.close();
}
}
public class Usuario {
private String nome;
private int idade;
public Usuario(String nomeUsuario, int serial) {
super();
this.nome = nomeUsuario;
this.idade = serial;
}
@Override
public String toString() {
return nome + " - " + idade;
}
public String getNome() {
return this.nome;
}
public int getIdade() {
return this.idade;
}
public void setNome(String nome) {
this.nome = nome;
}
public void setIdade(int idade) {
this.idade = idade;
}
}
public class Test {
public static void main(String[] args) {
// TODO code application logic here
ManipuladorXml xml =new ManipuladorXml();
List<Usuario>usuarios = new ArrayList<>();
Usuario u = new Usuario("test1", 1);
Usuario u1 = new Usuario("teste2", 3);
Usuario u2 = new Usuario("test3", 4);
usuarios.add(u);
usuarios.add(u1);
usuarios.add(u2);
xml.gravarXml(usuarios,"usuarios");
try {
xml.lerXml("usuarios");
} catch (FileNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
if we think that Xmlé is just a standardization, you can generate as a string in the pattern you want and then save with the XML extension.
– GabrielLocalhost
Put more examples of your code so we can help, where these values come from, want to save how and where? Leave the most complete question possible
– GabrielLocalhost