Android: Serialization of XML data

Source: Internet
Author: User
Tags requires serialization backup

What is XML?

First let's take a look at what XML is. XML, Extensible Markup Language (extensible Markup Language), used to mark an electronic file with a structured markup language that can be used to mark data, define data types, is a source language that allows users to define their own markup language, which is explained by Baidu Encyclopedia. While XML is a common format for transferring data across the Internet, it is SGML (the standard Universal Markup Language), like HTML, that requires XML knowledge if you need to access data over the Internet or send data to a Web service. The Android app needs to interact with the network, or it's just a stand-alone, non-interactive application, so it's likely that XML will be used in the development of Android applications.

Because of the strong extensibility of XML, which requires a stable base rule to support extensions, the syntax rules need to be noted:

    1. Start and end tag matches.
    2. Nested labels cannot be nested with each other.
    3. Case sensitive.

XML serialization

When you get a piece of data, if you need to serialize it into XML format, there are usually two ways:

    1. Serializes an XML data in the form of a concatenation string.
    2. Serializes an XML data using the XmlSerializer class.

The way to use the stitching string is simple, it is a manual work, the need to serialize the object, according to a certain format to serialize. Here's an example to illustrate how to stitch a string, simulate the contact data in the example, serialize it to XML, and save it on the SD card.

 1 private void BackupToContact1 () {2 StringBuilder sbuilder=new StringBuilder ();
 3//Set XML Data Header 4 Sbuilder.append ("<?xml version=" 1.0 "encoding=" Utf-8 "?>");
 5 Sbuilder.append ("<contacts>"); 6//Traverse contact information 7 for (contacts contact:contacts) {8 if (contact!=null) {9 sbuild
Er.append ("<contact id= '" +contact.getid () + "' >");
Ten Sbuilder.append ("<name>");
One sbuilder.append (Contact.getname ());
Sbuilder.append ("</name>");
Sbuilder.append ("<number>");
Sbuilder.append (Contact.getnumber ());
Sbuilder.append ("</number>");
Sbuilder.append ("<address>");
Sbuilder.append (Contact.getaddress ());
Sbuilder.append ("</address>");                21 22 Sbuilder.append ("</contact>");
Sbuilder.append ("</contacts>"); A try {27/////Create an XML file on an SD card (environment.getexternalstoragedirector
Y (), "Backup1.xml");
FileOutputStream fos=new fileoutputstream (file);
30//write serialized data to XML file Fos.write (Sbuilder.tostring (). GetBytes ());
Fos.close ();
Toast.maketext (Mainactivity.this, "Backup succeeded", 0). Show (); The catch (IOException e) {toast.maketext (Mainactivity.this, "Backup Failed", 0). Show (): E.
Printstacktrace (); Panax} 

When you are done, you can export the XML file on the SD card to your computer and view its contents.

For stitching strings, it can be seen that error prone, especially if there is a property value within each tag, you need to be careful. And if the contents of a particular symbol, such as "<, >", will result in XML serialization of XML file errors, and the use of XmlSerializer to serialize the XML file does not exist.

The second way is to serialize XML through the XmlSerializer class. Well, let's see. Xmlserializer,xmlserializer is primarily the serialization of XML as a stream of data, and it is an interface type that cannot be instantiated directly, and requires a static method Xml.newserializer () to get the object.

Here are some common methods:

    • Setoutput (outputstream,string): sets the output stream, as well as the encoding format.
    • Startdocument (String,boolean): The first parameter sets the encoding format of the document, and the second parameter setting is a separate document, which is generally set to true.
    • Enddocument (): Marks the end of an XML document, the XML document label appears in pairs, and ends.
    • Starttag (string,string): The beginning of an XML tag, the first parameter is a namespace, generally null, and the second parameter is the sign.
    • Endtag (string,string): The end of an XML tag, the first parameter is a namespace, generally null, the second parameter is the signature, the beginning and the beginning.
    • Attribute (string,string,string): Sets the property of a label, the first parameter is a namespace, the second parameter is the property name, and the third parameter is the property value.

The common methods of XmlSerializer are described above, and the following is an example to illustrate the use of XmlSerializer. The functionality implemented in the example is consistent with the concatenation of the string serialization XML above, which is serialized as the contact information for impersonation, and then stored on the SD card in XML format.

 1 private void BackupToContact2 () {2 try {3////Create a file on the SD card 4 files File=new
 File (Environment.getexternalstoragedirectory (), "Backup2.xml");
 5 FileOutputStream fos=new FileOutputStream (file);
 6//Get a XmlSerializer 7 XmlSerializer serializer = Xml.newserializer ();
8//Set XML output stream and encoding format 9 serializer.setoutput (FOS, "utf-8");
10//Set the beginning of the document, as well as the encoding format one serializer.startdocument ("Utf-8", true);
12 13//start tag serializer.starttag (null, "Contacts");                 for (contacts contact:contacts) {Serializer.starttag (null, "contact"); 17
Set the id attribute of the contact label to Serializer.attribute (NULL, "id", Contact.getid () + "");
Serializer.starttag (NULL, "name");
Serializer.text (Contact.getname ());
Serializer.endtag (NULL, "name");        22         
Serializer.starttag (NULL, "number");
Serializer.text (Contact.getnumber ());
Serializer.endtag (NULL, "number");
Serializer.starttag (NULL, "address");
Serializer.text (Contact.getaddress ());
Serializer.endtag (NULL, "address");
Serializer.endtag (NULL, "contact");
31} 32//An end tag of Serializer.endtag (NULL, "Contacts");
34//The end of the tag document (serializer.enddocument);
36//Close output flow of fos.close ();
Toast.maketext (Mainactivity.this, "Backup succeeded", 0). Show (); M catch (Exception e) {e.printstacktrace (); Toast.maketext (Mainactivity.this, "prepared
Failed ", 0). Show (); } 

After the save is successful, you can export the XML file to view its contents through the File Explorer, which is the same as the serialized XML file for the previous two examples, as follows:

 1 <?xml version= "1.0" encoding= "Utf-8"?> 2 <contacts> 3 <contact id= "0" > 4 <name>damon0&
 Lt;/name> 5 <number>18600000000</number> 6 <address>beijing0</address> 7 </contact> 8 <contact id= "1" > 9 <name>Damon1</name> ten <number>18600000001</number> <address& gt;beijing1</address> </contact> <contact id= "2" > <name>Damon2</name> < Number>18600000002</number> <address>beijing2</address> </contact> <contact ID = "3" > <name>Damon3</name> <number>18600000003</number> <address>beijing3 </address> </contact> <contact id= "4" > <name>Damon4</name> <number> 18600000004</number> <address>beijing4</address> </contact> <contact id= "5" > 29 <name>Damon5</name> <number>18600000005</number> <address>beijing5</address> </contact> <contact id= "6" > <name >Damon6</name> <number>18600000006</number> 37 <address>beijing6</address> </contact> <contact id= "7" > $ <number>18600000007</number > <address>beijing7</address> <contact </contact> id= "8" > <name>Damon8<
/name> <number>18600000008</number> <address>beijing8</address> $ </contact> <contact id= "9" > <name>Damon9</name> m <number>18600000009</number> $ < Address>beijing9</address> </contact> </contacts> 

In the example, the SD card is accessed, so you need to include the SD card write permission in the manifest file:

1     <uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>
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.