如何利用Android XmlSerializer生成XML文件

参考文章:

http://www.anddev.org/write_a_simple_xml_file_in_the_sd_card_using_xmlserializer-t8350.html

解析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");
        }
    }
复制代码

  实际上还有一种笨方法,只不过我没有试:那就是直奔普通字符文本写入文件就可以解决这个问题。不过这样要稍微麻烦些。


网上还有一个例子:

  1. private String produceXml(){  
  2.           
  3.         StringWriter stringWriter = new StringWriter();  
  4.         ArrayList<Beauty> beautyList = getData();  
  5.         try {  
  6.             // 获取XmlSerializer对象  
  7.             XmlPullParserFactory factory = XmlPullParserFactory.newInstance();  
  8.             XmlSerializer xmlSerializer = factory.newSerializer();  
  9.             // 设置输出流对象  
  10.             xmlSerializer.setOutput(stringWriter);  
  11.             /* 
  12.              * startDocument(String encoding, Boolean standalone)encoding代表编码方式 
  13.              * standalone  用来表示该文件是否呼叫其它外部的文件。 
  14.              * 若值是 ”yes” 表示没有呼叫外部规则文件,若值是 ”no” 则表示有呼叫外部规则文件。默认值是 “yes”。 
  15.              */  
  16.             xmlSerializer.startDocument("utf-8"true);  
  17.             xmlSerializer.startTag(null"beauties");  
  18.             for(Beauty beauty:beautyList){  
  19.                 /* 
  20.                  * startTag (String namespace, String name)这里的namespace用于唯一标识xml标签 
  21.                  *XML 命名空间属性被放置于某个元素的开始标签之中,并使用以下的语法: 
  22.                     xmlns:namespace-prefix="namespaceURI" 
  23.                     当一个命名空间被定义在某个元素的开始标签中时,所有带有相同前缀的子元素都会与同一个命名空间相关联。 
  24.                     注释:用于标示命名空间的地址不会被解析器用于查找信息。其惟一的作用是赋予命名空间一个惟一的名称。不过,很多公司常常会作为指针来使用命名空间指向某个实存的网页,这个网页包含着有关命名空间的信息。 
  25.                  */  
  26.                 xmlSerializer.startTag(null"beauty");  
  27.                   
  28.                 xmlSerializer.startTag(null"name");  
  29.                 xmlSerializer.text(beauty.getName());  
  30.                 xmlSerializer.endTag(null"name");  
  31.                   
  32.                 xmlSerializer.startTag(null"age");  
  33.                 xmlSerializer.text(beauty.getAge());  
  34.                 xmlSerializer.endTag(null"age");  
  35.                   
  36.                 xmlSerializer.endTag(null"beauty");  
  37.             }  
  38.             xmlSerializer.endTag(null"beauties");  
  39.             xmlSerializer.endDocument();  
  40.         } catch (Exception e) {  
  41.             e.printStackTrace();  
  42.         }  
  43.         return stringWriter.toString();  
  44.   
  45.     }  


-------------------------------------------------------------------------------------------------

点击打开链接:http://blog.csdn.net/zeng622peng/article/details/5864849

经常在Http Post Xml请求的时候,需要如何拼装XML数据,在Android中如何来做的呢,通常我们使用FastXmlserializer这个类。比如要拼装如下的XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Request xmlns="http://www.demo.com">
  
<operation>GetCustomerTariffInfo</operation>
  
<CustomerTariffInfoRequest>
     
<msisdn>44079324110</msisdn>
     
<detailsInfo>true</detailsInfo>
  
</CustomerTariffInfoRequest>
</Request>

 

代码如下

try {
            ByteArrayOutputStream 
out = new ByteArrayOutputStream();
            XmlSerializer serializer 
= new FastXmlSerializer();
            serializer.setOutput(
out"utf-8");
           
           
//  true可以让stanalone为Yes.
            serializer.startDocument("utf-8"true);
           
            serializer.setFeature(
"http://xmlpull.org/v1/doc/features.html#indent-output"true);
            serializer.startTag(
null"request");
           
//设置属性
            serializer.attribute(null,"xmlns","http://www.demo.com");
            serializer.text(
"/n");
           
            serializer.startTag(
null"account");
            serializer.text(
"");
            serializer.endTag(
null"account");
            serializer.startTag(
null"nickname");
            serializer.text(
"");
            serializer.endTag(
null"nickname");
            serializer.startTag(
null"password");
            serializer.text(
"");
            serializer.endTag(
null"password");
           
            serializer.endTag(
null"request");
            serializer.endDocument();
           
            
out.flush();
            
return out.toByteArray();
       
        } 
catch (Exception e) {
            e.printStackTrace();
        }


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值