注: 需要借助第三方kxml2-2.3.0.jar和xmlpull_1_1_3_4c.jar文件
public class Student { private String sid; private String name; private int age; private double score; public String getSid() { return sid; } public void setSid(String sid) { this.sid = sid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } @Override public String toString() { return "Student [sid=" + sid + ", name=" + name + ", age=" + age + ", score=" + score + "]"; } }
import java.io.FileOutputStream; import org.xmlpull.v1.XmlPullParserFactory; import org.xmlpull.v1.XmlSerializer; import com.loaderman.domain.Student; /** * 写入数据 * @author super * */ public class PullDemo4 { public static void main(String[] args) throws Exception { Student stu = new Student(); stu.setSid("s003"); stu.setName("赵六"); stu.setAge(66); stu.setScore(66.6); //1.创建解析器工厂 XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); //2.获取解析器 XmlSerializer serializer = factory.newSerializer(); //3.设置输出流 serializer.setOutput(new FileOutputStream("s.xml"), "utf-8"); //4.写入文档声明 serializer.startDocument("utf-8", true); serializer.startTag(null, "students"); serializer.startTag(null, "student"); serializer.attribute(null, "sid", stu.getSid()); serializer.startTag(null, "name"); serializer.text(stu.getName()); serializer.endTag(null, "name"); serializer.startTag(null, "age"); serializer.text(String.valueOf(stu.getAge())); serializer.endTag(null, "age"); serializer.startTag(null, "score"); serializer.text(String.valueOf(stu.getScore())); serializer.endTag(null, "score"); serializer.endTag(null, "student"); serializer.endTag(null, "students"); //写入结束文档 serializer.endDocument(); } }