Android里利用XmlSerializer生成xml文件
2012-05-26 14:18:14 来源:WEB开发网核心提示:解析xml文件的的文章很多,但是Android里生成xml文件的文章就很少了,Android里利用XmlSerializer生成xml文件,偶然机会找到一篇相关发面的文章,就分享一下了:用到的主要是XmlSerializer
解析xml文件的的文章很多,但是Android里生成xml文件的文章就很少了。偶然机会找到一篇相关发面的文章,就分享一下了:
用到的主要是XmlSerializer,利用它来写xml文件。
private static void XmlFileCreator(List<JokeBean> data){ File newxmlfile = new File(Environment.getExternalStorageDirectory()+"/new.xml"); try{ if(!newxmlfile.exists()) newxmlfile.createNewFile(); }catch(IOException e){ Log.e("IOException", "exception in createNewFile() method"); } //we have to bind the new file with a FileOutputStream FileOutputStream fileos = null; try{ fileos = new FileOutputStream(newxmlfile); }catch(FileNotFoundException e){ Log.e("FileNotFoundException", "can't create FileOutputStream"); } //we create a XmlSerializer in order to write xml data XmlSerializer serializer = Xml.newSerializer(); try { //we set the FileOutputStream as output for the serializer, using UTF-8 encoding serializer.setOutput(fileos, "UTF-8"); //Write <?xml declaration with encoding (if encoding not null) and standalone flag (if standalone not null) serializer.startDocument(null, Boolean.valueOf(true)); //set indentation option serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); //start a tag called "root" serializer.startTag(null, "jokes"); for(JokeBean joke:data){ serializer.startTag(null, "joke"); //i indent code just to have a view similar to xml-tree serializer.startTag(null, "id"); serializer.text(joke.getId()); serializer.endTag(null, "id"); serializer.startTag(null, "title"); serializer.text(joke.getTitle()); //set an attribute called "attribute" with a "value" for <child2> //serializer.attribute(null, "attribute", "value"); serializer.endTag(null, "title"); serializer.startTag(null, "text"); //write some text inside <text> serializer.text(joke.getText()); serializer.endTag(null, "text"); serializer.endTag(null, "joke"); } serializer.endTag(null, "jokes"); serializer.endDocument(); //write xml data into the FileOutputStream serializer.flush(); //finally we close the file stream fileos.close(); } catch (Exception e) { Log.e("Exception","error occurred while creating xml file"); } }
Tags:Android 利用 XmlSerializer
编辑录入:爽爽 [复制链接] [打 印]- ››Android 当修改一些代码时,使用什么编译命令可以最...
- ››Android 如何添加一个apk使模拟器和真机都编译进去...
- ››Android 修改Camera拍照的默认保存路径
- ››Android 如何修改默认输入法
- ››android开发中finish()和System.exit(0)的区别
- ››Android手势识别简单封装类
- ››android中查看项目数字证书的两种方法
- ››Android中获取IMEI码的办法
- ››android 相机报错 setParameters failed
- ››Android重启运用程序的代码
- ››Android为ListView的Item设置不同的布局
- ››android bitmap与base64字符串的互相转换
更多精彩
赞助商链接