序列化xml文件
//测试类
package com.heima.serializerXML;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;
public class SerializerXML {
/**
* 序列化XML文件,把java文件写到xml中
* 1.创建解析器工厂
* 2.通过解析器工厂创建解析器(序列化Serialiazer)
* 3.输出流
* 4.封装解析器
* @throws Exception
*/
public static void main(String[] args) throws Exception {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlSerializer serializer = factory.newSerializer();
OutputStream os = new FileOutputStream("src/employee1.xml");
serializer.setOutput(os, "utf-8");
//开始序列化
serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
serializer.startDocument(null, true);
serializer.startTag(null, "employees");
serializer.startTag(null, "employee");
serializer.startTag(null, "name");
serializer.text("张三");
serializer.endTag(null, "name");
serializer.startTag(null, "dept");
serializer.text("安卓开发");
serializer.endTag(null, "dept");
serializer.startTag(null, "sal");
serializer.text("15000");
serializer.endTag(null, "sal");
serializer.endTag(null, "employee");
serializer.endTag(null, "employees");
serializer.endDocument();
}
}
//用于序列化的文件
package com.heima.serializerXML;
public class Employee {
private String name;
private String dept;
private String sal;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public String getSal() {
return sal;
}
public void setSal(String sal) {
this.sal = sal;
}
@Override
public String toString() {
return "Employee [name=" + name + ", dept=" + dept + ", sal=" + sal
+ "]";
}
}
//序列化后的xml文件
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<employees>
<employee>
<name>张三</name>
<dept>安卓开发</dept>
<sal>15000</sal>
</employee>
</employees>