代码语言:javascript复制
代码语言:javascript复制//获得序列化对象
XmlSerializer serializer = Xml.newSerializer();
try{
File path = new File(Environment.getExternalStorageDirectory(),"itcast.xml");
FileOutputStream fos = new FileOutPutStream(path);
//指定序列化对象输出的位置和编码
serializer.setOutput(fos,"utf-8");
//写XML文件的开头document声明:
//
serializer.startDocument("utf-8",true);
//根标签
serializer.startTag(null,"persons");
//循环写入子标签属性及内容
for(Person person : personList){
serializer.startTag(null,"person");
serializer.attribute(null,"id",String.valueOf(person.getId()));
//person标签的id属性,值为String,注意这里最好不要用int数后直接 ""转换为String,因为那样做其实需要new一个StringBuffer出来,操作次数多了浪费时间空间
serializer.startTag(null,"name");
serializer.text(person.getName());
serializer.endTag(null,"name");
serializer.endTag(null,"person");
}
//结束根标签
serializer.endTag(null,"persons");
//结束document
Serizlizer,endDocument();
}catch(Exception e){
e.printStackTrace}
}
2.本地XML文件的pull解析
代码语言:javascript复制File path = new File(Environment.getExternalStorageDirectory(),"itcast.xml");
FileInputStream fis = new FileInputStream(path);
//获得pull解析器对象
XmlPullParser parser = Xml.newPullParser();
//指定解析的文件和编码格式
parser.setInput(fis,"utf-8");
//获得事件类型
int eventType = parser.getEventType();
//用于存放解析得到的数据
List
personList = null;
Person person = null;
String id;
while(eventType != XmlPullParser.END_DOCUMENT){
String tagName = parser.getName(); //获得当前节点名称
switch(eventType){
case XmlPullParser.START_TAG: //等于开始节点
、
if("persons".equals(tagName)){ //
personList = new ArrayList
(); }else if("person".equals(tagName)){ //
person = new Person(); id = parser.getAttributeValue(null,"id"); person.setId(Integer.valueOf(id)); }else if("name".equals(tagName)){
person.setName(parser.nextText()); }else if("age".equals(tagName)){
person.setAge(Integer.parseInt(parser.nextText())); break; case XmlPullParser.END_TAG:{ //
if("person".equals(tagName)){
//把上面得到的Person对象添加到personList
personList.add(person);
}
break;
default:
break;
}
//获得下一个事件类型
eventType = parser.next();
}
}
}