第三方包:xstream-1.3.1.jar
1.序列号对象为xml
<span style="font-family:Arial;background-color: rgb(255, 255, 255);"> </span><pre class="html" name="code">XStream xStream = new XStream();
xStream.alias("person", Person.class);
xStream.alias("personnumber", PhoneNumber.class);
// Serializing an object to XML
Person joe = new Person("Joe", "Walnes");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));
FileOutputStream fileOutputStream;
String path = "/mnt/sdcard/test.xml";
File f = new File(path);
if (!f.exists())
f.createNewFile();
fileOutputStream = new FileOutputStream(f);
xStream.toXML(joe, fileOutputStream);
// Deserializing an object back from XM
// XStream xStream2 = new XStream();
fileOutputStream.close();2.反序列号xml为对象。注意用domdriver,并且alias、userAttributeFor,必须定义。不然报错。
XStream xStream2 = new XStream(new DomDriver());
xStream2.alias("person", Person.class);
xStream2.alias("personnumber", PhoneNumber.class);
xStream2.useAttributeFor(Person.class, "firstname");
xStream2.useAttributeFor(Person.class, "lastname");
xStream2.useAttributeFor(PhoneNumber.class, "code");
xStream2.useAttributeFor(PhoneNumber.class, "number");
FileInputStream fileInputStream = new FileInputStream(f);
Person person = (Person) xStream2.fromXML(fileInputStream);
String str = person.toString();
EditText t = (EditText) findViewById(R.id.editText1);
t.setText(str);
fileInputStream.close();
本文介绍如何使用XStream库将Java对象序列化为XML文件,并从XML文件中反序列化回Java对象。文章详细展示了配置XStream的过程,包括定义别名和属性映射,以及具体的代码实现。
476

被折叠的 条评论
为什么被折叠?



