In the article "Android Generate XML File" to write XML format file in the form of a stream, but there is a certain problem, that is, in the text message content can not appear in <> and other parentheses, this article uses the XML serializer to solve
XML Serializer Object
XmlSerializer xs = Xml.newserializer ();
* Set the output stream to the serializer
File File = new file (Environment.getexternalstoragedirectory (), "Backupsms.xml");
FileOutputStream fos = new FileOutputStream (file);
Specifying a good output stream for the serializer
Xs.setoutput (FOS, "utf-8");
* Start generating XML files
Xs.startdocument ("Utf-8", true);
Xs.starttag (NULL, "SMSS");
......
The code is as follows:
PackageCom.wuyudong.createxml;ImportJava.io.File;ImportJava.io.FileOutputStream;Importjava.util.ArrayList;Importjava.util.List;ImportOrg.xmlpull.v1.XmlSerializer;ImportCom.wuyudong.createxml.domain.Sms;ImportCOM.WUYUDONG.CREATEXML2.R;ImportAndroid.os.Bundle;Importandroid.os.Environment;Importandroid.app.Activity;Importandroid.util.Xml;ImportAndroid.view.View; Public classMainactivityextendsActivity {List<Sms>message; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); //Create 10 Virtual SMSMessage =NewArraylist<sms>(); for(inti = 0; I < 10; i++) {SMS SMS=NewSMS ("First" + i + "SMS", System.currenttimemillis () + "", "1", "" + i + i +i); Message.add (SMS); } } Public voidClick (View v) {File file=NewFile (Environment.getexternalstoragedirectory (),"Backup1.xml"); Try{FileOutputStream fos=Newfileoutputstream (file); //Get XML SerializerXmlSerializer xs =Xml.newserializer (); Xs.setoutput (FOS,"Utf-8"); //generating an XML headerXs.startdocument ("Utf-8",true); //add an XML root nodeXs.starttag (NULL, "message"); for(Sms sms:message) {Xs.starttag (NULL, "SMS"); Xs.starttag (NULL, "Body"); Xs.text (Sms.getbody ()); Xs.endtag (NULL, "Body"); Xs.starttag (NULL, "Date"); Xs.text (Sms.getdate ()); Xs.endtag (NULL, "Date"); Xs.starttag (NULL, "Address"); Xs.text (Sms.getaddress ()); Xs.endtag (NULL, "Address"); Xs.starttag (NULL, "type"); Xs.text (Sms.gettype ()); Xs.endtag (NULL, "type"); Xs.endtag (NULL, "SMS"); } Xs.endtag (NULL, "message"); //generating an XML headerxs.enddocument (); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); } }}
Android uses an XML serializer to generate an XML file