Element getXML()

package com.thinking.serializable;


import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;


import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Serializer;


/**
 *对象数据生成xml
 * @author zy
 *
 */
public class Person {
//成员属性
private String first ,last;
//构造方法,初始化成员变量
public Person(String first,String last){
this.first = first;
this.last = last;
}

//定义一个解析XML的方法,返回element
public Element getXML(){
//父节点
Element person = new Element("person");
//子节点:名
Element firstName = new Element("first");
//保存实例化的属性
firstName.appendChild(first);

Element lastName = new Element("last");
lastName.appendChild(last);

//父节点添加子节点
person.appendChild(firstName);
person.appendChild(lastName);

//返回对象给调用者
return person;
}

//Constructor to restore a Person from an XML Element
public Person(Element person){
//父节点获取子节点“first”的值
first = person.getFirstChildElement("first").getValue();
last = person.getFirstChildElement("last").getValue();
}

//格式化,一个输入流,一个文档对象
public static void format(OutputStream os,Document doc) throws Exception{
//Make it human-readable;
Serializer serializer = new Serializer(os,"ISO-8859-1");
serializer.setIndent(2);
serializer.setMaxLength(60);
serializer.write(doc);
serializer.flush();
}

public static void main(String[] args) throws Exception {
List<Person> people = Arrays.asList(
//构造方法,创建对象
new Person("Dr. Bunsen","Honeydew"),
new Person("Gonzo","The Great"),
new Person("Phililp J.","Fry"));
System.out.println(people);

//设置根目录
Element root = new Element("people");
//遍历ArrayList数组集合中的对象数据
for (Person p : people) 
//读取子节点,并调用getXML()解析
root.appendChild(p.getXML());
//解析后的对象数据创建文档结构
Document doc =new  Document(root);
//格式化文档视图
format(System.out,doc);
//创建xml文件名,并放到缓存流中,同时再格式化一次
format(new BufferedOutputStream(new FileOutputStream("People.xml")), doc);
}

}

www.gxnnfp.com

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值