对象序列化的一个重要限制是它只是java的解决方案:只有java程序才能反序列化这种对象。一种更具互操作性的解决方案是将数据转换为XML方式,这可以使其被各种各样的平台和语言使用。因为XML非常流行,所以用它来编程时各种选择不胜枚举,包括随JDK发布的javax.xml.*类库。我们选择使用开源XOM类库(可从www.xom.nu下载并获得文档)
public class Person { private String first,last; public Person(String first,String last){ this.first=first; this.last=last; } public Element getXml(){ Element person=new Element("person"); Element firstName=new Element("first"); firstName.appendChild(first); Element lastName=new Element(); lastName.appendChild(last); person.appendChild(firstName); person.appendChild(lastName); return person; } public Person(Element person){ this.first=person.getFirstChildElement("first").getValue(); this.last=person.getFirstChildElement("last").getValue(); } public static void format(OutputStream os,Document doc) throws Exception { Serializer serializer=new Serializer(os,"ISO-8859-1"); serializer.setIndent(4); serializer.setMaxLength(60); serializer.write(doc); serializer.flush() } public static void main(String[] args) throws Exception{ List<Person> people= Arrays.asList(new Person("a","b"),new Person("c","d")); Element root=new Element("root"); for(Person obj:people) root.appendChild(obj.getXml()); Document doc=new Document(root); } }