XML

对象序列化的一个重要限制是它只是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);

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值