标签:start err and vat save layout 声明 except content
//最后两个实现的方作用是一样的
package com.itheima.xmlseralizer; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import javax.xml.XMLConstants; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlSerializer; import android.app.Activity; import android.os.Bundle; import android.util.Xml; import android.view.View; public class MainActivity extends Activity { ArrayList<SMS> smsList = new ArrayList<SMS>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); for(int i = 0;i<30;i++){ SMS sms = new SMS(); sms.from= "10000"+i; sms.content="content"+i; sms.time="2016-9-4 16:25:"+i; smsList.add(sms); } for(SMS sms: smsList){ System.out.println(sms); } } public void saveSMS(View v){ StringBuilder sb = new StringBuilder(); //写xml的文档声明 sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); sb.append("<SMSList>"); for(SMS sms:smsList){ //写每一个sms开始的标签 sb.append("<SMS>"); //一个属性一个属性写对应的节点 sb.append("<from>"); sb.append(sms.from); sb.append("</from>"); sb.append("<content>"); sb.append(sms.content); sb.append("</content>"); sb.append("<time>"); sb.append(sms.time); sb.append("</time>"); sb.append("</SMS>"); } sb.append("</SMSList>"); String xml = sb.toString(); try { FileOutputStream fos = openFileOutput("sms.xml", MODE_PRIVATE); fos.write(xml.getBytes()); fos.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void saveSMS2(View v){ //获取xml序列化器 XmlSerializer serializer = Xml.newSerializer(); //给序列化器设置一个输出 try { serializer.setOutput(openFileOutput("smslist.xml", MODE_PRIVATE), "utf-8"); //写文档开始的声明<?xml version="1.0"?> serializer.startDocument("utf-8", true); //第一个参数 名称空间 如果当前文档受某份schema约束就传入一个名称空间 没有约束的情况传null //<SMSList> serializer.startTag(null, "SMSList"); for(SMS sms:smsList){ //写<SMS> serializer.startTag(null, "SMS"); serializer.startTag(null, "from"); serializer.text(sms.from); serializer.endTag(null, "from"); serializer.startTag(null, "content"); serializer.text(sms.content); serializer.endTag(null, "content"); serializer.startTag(null, "time"); serializer.text(sms.time); serializer.endTag(null, "time"); //</SMS> serializer.endTag(null, "SMS"); } //</SMSList> serializer.endTag(null, "SMSList"); serializer.endDocument(); } catch (Exception e) { e.printStackTrace(); } }
标签:start err and vat save layout 声明 except content
原文地址:https://www.cnblogs.com/wulinmiao/p/12199785.html