根据对象生成XML文档.
使用Java提供的java.beans.XMLEncoder和java.beans.XMLDecoder类。
这是JDK 1.4以后才出现的类
步骤:
(1)实例化XML编码器
XMLEncoder xmlEncoder = new XML Encoder(new BufferedOutputStream(new
FileOutputStream(new File(“a.xm)”)));
(2)输出对象
(3)关闭
代码示例:
package com.booy;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.Xpp3Driver;
import org.junit.jupiter.api.Test;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.*;
public class XMToolsDemo {
//把对象转成XML文件写入
@Test
public void xmlEncoder(){
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("test.xml"));
//生成xmlEncoder对象
XMLEncoder xmlEncod = new XMLEncoder(bos);
Person p = new Person();
p.setPersonid("110");
p.setName("jack");
p.setAddress("山的那边");
p.setTel("18888888888");
p.setEmail("admin@qq.com");
p.setFax("18888888888");
//把对象写入xml里
xmlEncod.writeObject(p);
xmlEncod.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
//从XML文件读取对象
@Test
public void xmlDecoder(){
try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("test.xml"));
//生成xmlDecoder对象
XMLDecoder xmlDecod = new XMLDecoder(bis);
Person p = (Person)xmlDecod.readObject();
System.out.println(p);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
//使用第三方组件XStream
@Test
public void xStream(){
Person p = new Person();
p.setPersonid("110");
p.setName("jack");
p.setAddress("山的那边");
p.setTel("18888888888");
p.setEmail("admin@qq.com");
p.setFax("18888888888");
//通过驱动构建一个xStream对象
XStream xStream = new XStream(new Xpp3Driver());
//修改别名Person.class为person
xStream.alias("person",Person.class);
//为Person设置属性
xStream.useAttributeFor(Person.class,"personid");
//生成xml文件
String xml = xStream.toXML(p);
System.out.println(xml);
//解析xml
Person person = (Person)xStream.fromXML(xml);
System.out.println(person);
}
}
对象数据类:
package com.booy;
public class Person {
private String personid;
private String name;
private String address;
private String tel;
private String fax;
private String email;
public String getPersonid() {
return personid;
}
public void setPersonid(String personid) {
this.personid = personid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Person{" +
"personid='" + personid + '\'' +
", name='" + name + '\'' +
", address='" + address + '\'' +
", tel='" + tel + '\'' +
", fax='" + fax + '\'' +
", email='" + email + '\'' +
'}';
}
}