JAVA XML 开源工具 XOM 很好用

本文详细介绍了Java中序列化与反序列化的原理、API使用及常见操作,包括序列化对象到文件、输出流,以及从文件、输入流中反序列化对象。通过实例演示了如何自定义序列化类,以及在不同场景下如何灵活运用这些技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

/**序列化**/
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;

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

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("last");
		lastName.appendChild(last);
		person.appendChild(firstName);
		person.appendChild(lastName);
		return person;
	}
	public Person(Element person){
		first = person.getFirstChildElement("first").getValue();
		last = person.getFirstChildElement("last").getValue();
	}
	public String toString(){
		return first + " " + last;
	}
	public static void format(OutputStream os,Document doc)throws Exception{
		Serializer serializer = new Serializer(os,"UTF-8");
		serializer.setIndent(4);//怎么缩进
		serializer.setMaxLength(600);
		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("Phillip", "Fry"));
		System.out.println(people);
		Element root = new Element("people");
		for(Person p : people){
			root.appendChild(p.getXML());
		}
		Document doc = new Document(root);
		format(System.out, doc);
		format(new BufferedOutputStream(new FileOutputStream("People.xml")), doc);
	}
}
/**反序列化**/

import java.io.IOException;
import java.util.ArrayList;

import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.Elements;
import nu.xom.ParsingException;
import nu.xom.ValidityException;

public class People extends ArrayList<Person>{

	public People(String xmlFile) throws ValidityException, ParsingException, IOException{
		Document document = new Builder().build(xmlFile);
		Elements eles = document.getRootElement().getChildElements();
		for(int i = 0 ; i < eles .size(); i++){
			add(new Person(eles.get(i)));
		}
	}
	public static void main(String[] args) throws ValidityException, ParsingException, IOException {
		People people = new People("People.xml");
		System.out.println(people);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值