一、将数据转换为XML格式
(1)导包
使用的IDE:IDEA16
创建lib,添加进路径
xom包:http://www.xom.nu/
(2)coding
(3)输出
二、从XML文件中反序列化Person对象
(1)coding
注意:会报异常
因为:从xom-1.2.10.jar开始使用file协议,所以添加全路径,如下图
(2)输出
package Test;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Serializer;
import javax.print.Doc;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
/**
* Created by donal on 2017/2/12.
*/
public class Person
private String first, last;
public Person(String first, String last){
this.first = first;
this.last = last;
}
//Produce an XML Element from this Person object:
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 = person.getFirstChildElement("first").getValue();
last = person.getFirstChildElement("last").getValue();
}
public String toString(){
return first + " " + last;
}
//Make it human-readable:
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("Dr.Bumsen", "Honeydew"),
new Person("Gonzo", "The Great"),
new Person("Phillip J.", "Fly")
);
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"
package Test;
import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Elements;
import java.util.ArrayList;
/**
* Created by donal on 2017/2/12.
*/
public class People extends ArrayList<Person>{
public People(String fileName) throws Exception{
Document doc = new Builder().build(fileName);
Elements elements = doc.getRootElement().getChildElements();
for (int i = 0; i < elements.size(); ++i){
add(new Person(elements.get(i)));
}
}
public static void main(String []args) throws Exception {
People p = new People("file:\\D:\\tools\\Code\\Java\\IDEA\\JavaSE\\XMLTest\\People.xml");
System.out.println(p);
}
}