A tutorial on using XmlSerializer to serialize XML data in Android applications _android

Source: Internet
Author: User
Tags serialization

First, let's take a look at what is Serializer,serializer and serialization. It's not just a simple way to keep objects in memory, it allows us to transfer objects in a stream so that objects can be passed like basic data.
XmlSerializer is a class library for XML serialization, let's take a look at the common methods inside:

Basic methods
1. Creates a serializer of an XML file that returns an XML serializer object.

XmlSerializer = Xml.newserializer ();

2. Set the output path and encoding of the serializer

FileOutputStream = new FileOutputStream (new file (Environment.getexternalstoragedirectory (), "filename. xml"));
Xmlserializer.setoutput (FileOutputStream, "code");

3. Declaring the XML file header (written to the declaration header in the XML file)

Serializer.startdocument ("XML declaration encoding", whether the document is independent);

4. Declaring child nodes

Serializer.starttag (namespace,string "section name");

5. Declaring node properties

Serializer.attribute (namespace, attribute name, attribute value);

6. Declaring the Textnode in the node

Serializer.txt (text value);

7. Set the tail tag of the node

Serializer.endtag (name space, "node call");

8. The end of the write XML file means that the XML file ends.

Serializer.enddocument ();

9. Closing Resources

Fileoutputstream.close ();

Example

The final effect diagram above
Now paste the main code:

Main.xml

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= 
"http://schemas.android.com/apk/" Res/android " 
  android:orientation=" vertical " 
  android:layout_width=" fill_parent " 
  android:layout_" height= "Fill_parent" 
  > 
<textview  
  android:layout_width= "fill_parent"  
  android:layout_ height= "Wrap_content"  
  android:id= "@+id/textview" 
  /> 
</LinearLayout> 

The code for the activity

Package Cn.com.xmlseriliazer; 
Import Java.io.StringWriter; 
 
Import java.util.ArrayList; 
Import Org.xmlpull.v1.XmlPullParserFactory; 
 
Import Org.xmlpull.v1.XmlSerializer; 
Import android.app.Activity; 
Import Android.os.Bundle; 
Import Android.widget.TextView; /** * * @author Chenzheng_java * @description Test generates an XML file through Xmlserilizer * @since 2011/03/03 * */public class X Mlserializeractivity extends activity {@Override public void onCreate (Bundle savedinstancestate) {Super.oncre 
    Ate (savedinstancestate); 
     
    Setcontentview (R.layout.main); 
    String result = Producexml (); 
    TextView TextView = (TextView) This.findviewbyid (R.id.textview); 
     
  Textview.settext (result); /** * * * @return The string representation of the generated XML file */private string Producexml () {StringWriter StringWriter = 
    New StringWriter (); 
    arraylist<beauty> beautylist = GetData (); try {//Get XmlSerializer object Xmlpullparserfactory factory = XmlPullparserfactory.newinstance (); 
      XmlSerializer XmlSerializer = Factory.newserializer (); 
      Set the output Stream object Xmlserializer.setoutput (StringWriter); 
       * * Startdocument (String encoding, Boolean Standalone) encoding representing the encoding * Standalone is used to indicate whether the file is calling other external files. * If the value is "yes", the external rule file is not called, and if the value is "no", the call external rule file is indicated. 
       The default value is yes. 
      * * Xmlserializer.startdocument ("Utf-8", true); 
      Xmlserializer.starttag (NULL, "beauties"); 
         for (Beauty beauty:beautylist) {/* * Starttag (string namespace, string name) The namespace here is used to uniquely identify XML tags The *xml namespace attribute is placed in the start tag of an element and uses the following syntax: xmlns:namespace-prefix= "NamespaceURI" when a namespace is defined at the beginning of an element 
          Label, all child elements with the same prefix are associated with the same namespace. Note: Addresses used to mark namespaces are not used by the parser to find information. Its only function is to give the namespace a unique name. 
         However, many companies often use namespaces as pointers to point to an existing Web page that contains information about namespaces. 
         
        * * Xmlserializer.starttag (NULL, "Beauty"); 
        Xmlserializer.starttag (NULL, "name"); Xmlserializer.text(Beauty.getname ()); 
         
        Xmlserializer.endtag (NULL, "name"); 
        Xmlserializer.starttag (NULL, "age"); 
        Xmlserializer.text (Beauty.getage ()); 
         
        Xmlserializer.endtag (NULL, "age"); 
      Xmlserializer.endtag (NULL, "Beauty"); 
      } Xmlserializer.endtag (NULL, "beauties"); 
    Xmlserializer.enddocument (); 
    catch (Exception e) {e.printstacktrace (); 
 
  return stringwriter.tostring (); /** * * @return contains a lot of beautiful information collection * * * private arraylist<beauty> GetData () {Arraylist<beaut 
     
    y> beautylist = new arraylist<beauty> (); 
    Beauty Yangmi = new Beauty ("Yang", "23"); 
 
    Beauty linzhiling = new Beauty ("Lin Chi Ling", "28"); 
    Beautylist.add (YANGMI); 
     
    Beautylist.add (linzhiling); 
  return beautylist; 
    }/** * * @author Chenzheng_java * Beauty entity class/Private class beauty{String name; 
    String age; 
    Public String GetName () {  return name; 
    public void SetName (String name) {this.name = name; 
    Public String Getage () {return age; 
    public void Setage (String age) {this.age = age; 
    @Override public String toString () {return "Beauty [age= + Age +", name= "+ name +"] "; 
      Beauty (string name, String age) {this.name = name; 
    This.age = age; 

 Public Beauty () {}}}

The others are default.

As we can see from the code, it is also fairly easy to generate XML using XmlSerializer. The basic steps are almost the same as parsing XML. There's not much to talk about here. For more information, see the API.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.