Android platform detailed explanation of XML file parsing and writing method based on pull mode _android

Source: Internet
Author: User
Tags flush sqlite sqlite database

This paper describes in detail the method of parsing and writing XML files based on pull mode of the Android platform. Share to everyone for your reference, specific as follows:

XML technology has been widely used in data interaction across platforms, and if we need to develop an Android application that requires data interaction with the server, the XML file makes it easy to transfer information between the Android platform and the server. The implementation involves the technology of parsing and writing XML files. This paper realizes the technology of parsing XML files on the Android platform based on pull mode.

Xmlpullparser is a Java implementation of the Open Source API package (source download address http://www.xmlpull.org/), implemented a pull way to parse the XML file, the Android SDK contains the API, You need to import the following three packages when you use:

Import org.xmlpull.v1.xmlpullparser;//contains package import org.xmlpull.v1.xmlpullparserexception;//parsing XML file classes
exception
handling importorg.xmlpull.v1.xmlserializer;//contains packages written to XML file classes

We take SQLite database class practice in the data class people as an example, the People class has 4 attributes: Id,name,age,height, assuming that there is a test data id=1,name= "Du Fu", age=30,height=1.75,

The corresponding data item elements in the XML file are as follows:

<peopleinfo>
  <peopletag= "item1" >
    <id>1</id>
    <name> Dufu's </name>
    <age>30</age>
     
 

1. Use Xmlpullparser to resolve the file

First you need to initialize a Xmlpullparser object Parser,r.xml.peopleinfo the identity of the file Peopleinfo.xml in the project, and then the elements in the file are parsed step-by-step after reading the file.

Xmlpullparser parser= getresources (). GETXML (R.xml.peopleinfo);

The relevant functions of the Xmlpullparser and the description are as follows:

Related functions or variables

Description

Example

Xmlpullparser. start_document

Document start identification, root element

<peopleinfo>

Xmlpullparser. end_document

Document End Identification

</peopleinfo>

Xmlpullparser. Start_tag

Element start identification

<people>

Xmlpullparser. End_tag

Element End Identity

</people>

Geteventtype ()

Gets the type of element ( such as Start_tag, End_tag, TEXT, etc.)

such as <peopleinfo>

The type is start_document

Next ()

Gets the next unresolved element

Event representation <> an item in parentheses

GetName ()

Gets the name of the current element

if read to <age>, the return value is "age"

Nexttext ()

Returns the text value corresponding to the current element

If the event is

Getattributename (int index)

Gets the name of the property in the current element

such as tag

Getattributevalue (int index)

Gets the value of the property in the current element

such as "Item1"


Parsing steps:

1 Initialize parser, specify XML file
2 read document Start identification, root element <peopleinfo>
3 Read data item element Start logo, <people>
A to read the properties of the data item element, tag= "Item1"
b read the child elements of the data item, Id,name,age,height
4 The end of a data item, </PEOPLE>, save the result of the data item
5 read document End ID,</peopleinfo>

2. Use XmlSerializer to write XML files

The process of writing an XML file: Initializes a XmlSerializer object serializer, sets the writer object for the output, writes the data to serializer, and then writes the object to the file through writer.

XmlSerializer serializer = Xml.newserializer ();
Serializer.setoutput (writer);
... Writer.flush ()

The relevant functions of the XmlSerializer and the description are as follows:

Related functions

Description

Example

Setoutput (Writer Writer)

Set the output Writer Object

Startdocument (String encoding, Boolean standalone);

Write XML The start identification statement for the file, which must be Setoutput is invoked after

<?xml version= "1.0" encoding= "UTF-8" standalone= "yes"?>

Starttag (string namespace, string name);

Write start element identification

as <people>,<age>

Attribute (string namespace, string name, string value);

as tag= "People1"

Text (String text)

Write element values

such as: Du Fu

Endtag (string namespace, string name)

Write element End identity

as </people>,</age>

Enddocument ();

Write document END tag


Write Step:

1) Initialization of serializer
2) Set writer object writer
3 Write document start tag <?xml version= "1.0" encoding= "UTF-8" standalone= "yes"?>
4 Write root element <peopleinfo>
5 Write data item elements <people>
A) Write data item properties tag= "People1"
B writes the data item child element, Id,name,age,height
6 Write Data entry element Terminator </people>
7 Write root element terminator </peopleinfo>
8 Writing document Terminator
9 Write data to the file via writer, Writer.flush ()
10) Close Writer object

Implements a tool class Xmlpullhelper that provides parsing and writing to XML files

1. Specific implementation, the code is as follows:

Package Aaron.android.SQLiteDamon;
Import java.io.IOException;
Import Java.io.Writer;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import Java.util.Map;
Import Org.xmlpull.v1.XmlPullParser;
Import org.xmlpull.v1.XmlPullParserException;
Import Org.xmlpull.v1.XmlSerializer;
Import Android.util.Log;
  public class Xmlpullhelper {private Xmlpullparser parser;
  Private XmlSerializer serializer;
  Private arraylist<map<string, object>> contents=new arraylist<map<string,object>> ();
  Private map<string,object> Map=null;
    Public Xmlpullhelper (Xmlpullparser parser,xmlserializer serial) {this.parser=parser;
  This.serializer = serial; /** * The data of all nodes in the XML file is parsed and saved in a ArrayList return * @param nodename: The name of the data item, here is "people" * @param attr: Properties of the data item, such as Id,name, Age,height * @return Parse the results of the XML file data * @throws xmlpullparserexception * @throws ioexception * * Public Arraylis T<map<string,object>> xmlpull (String nodename,string[] attr) Throws Xmlpullparserexception, ioexception{//loop read all elements while (Parser.next ()!=xmlpullparser.end_document) {s
        Witch (Parser.geteventtype ()) {case XmlPullParser.START_DOCUMENT:break; The case xmlpullparser.start_tag:{//element begins to identify//determine whether the required data item, if it is, initializes a map to hold the value of the data item if (Parser.getname ()!=n
            Ull&&parser.getname (). Equals (NodeName)) {map=new hashmap<string, object> (); Iterates through all the attributes for the element for (int j=0;j<parser.getattributecount (); j + +) Map.put (parser.getattributename (j), Parser.getattributevalue (j));//Add the value of the property, such as tag= "Item1"} else if (Map!=null) {for (int i=0; i<attr.length;i++) {if (Parser.getname ()!=null&&parser.getname (). Equals (Attr[i])) {//Add values for child elements, such as <n
              Ame> John </name> Map.put (Attr[i],parser.nexttext ());
        }} break; Case Xmlpullparser.end_tag: {//element end ID//Determine whether the end of a data item, if so, add the data item's data to the dataset contents if (Parser.getname (). Equals (nodename) &&
            Map!=null) {contents.add (map);
          Map=null;
        } break;
  }} return contents; /** * Writes the given dataset to the XML file * @param filename: The root element name, which defaults to the same file name, such as "Peopleinfo" * @param nodename: Data item name such as "people" * @param attr: Properties of data items such as Id,name,age,height * @param con: Data set to be written * @throws xmlpullparserexception * @throws ioexcept Ion */public void Xmlwrite (String filename,string nodename,string[] attr,arraylist<map<string,object>> C
    On) throws Xmlpullparserexception, ioexception{serializer.startdocument ("UTF-8", true); Serializer.starttag (null, fileName);//start root element label <peopleinfo> for (int i=0;i<con.size (); i++) {//Start element label &
      Lt;people> Serializer.starttag (null, nodename);
      Tag People property Serializer.attribute (null, "tag", "people" +i); Loop writes child nodes to element Id,naMe,age,height for (int j=0;j<attr.length;j++) {Serializer.starttag (null, attr[j]);
        Serializer.text (Con.get (i). Get (Attr[j]). toString ());
      Serializer.endtag (NULL, attr[j]);
    }//End tags </people> serializer.endtag (null, nodename);
    }//end tag </peopleinfo> serializer.endtag (null, fileName);
  End document Tag serializer.enddocument ();

 }
}

1. Use the tool class Xmlpullhelper specific implementation

Defines the DataSet object contents to hold the data read from the XML file arraylist<map<string, object>> contents = null; Writes the data to an XML file and saves it to the SD card if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {file Sdcarddir
    = Environment.getexternalstoragedirectory ()//Get SDcard directory File savefile = new file (Sdcarddir, "peopleinfo.xml");
    FileWriter w=new FileWriter (savefile);
    XmlSerializer serializer = Xml.newserializer ();
    Xmlpullhelper xhelper=new Xmlpullhelper (Null,serializer);
    The child element tags to be written String []items={ID, ' name ', ' age ', ' height '};
    Passing the writer object to serializer Serializer.setoutput (W); Xhelper.xmlwrite ("Peopleinfo", "people", items, contents);//Call Write Method W.flush ();
Writes the data in the serializer to the file W.close ();
//Read the XML file, parse and save in the dataset contents Xmlpullparser parser = getresources (). GETXML (R.xml.peopleinfo);
Xmlpullhelper xhelper=new Xmlpullhelper (parser,null);
String []items={"id", "name", "Age", "height"}; try{Contents=xhelper.xmlpull ("People", items);//Call resolution method} catch (Exceptione) {log.e ("Xmlpullparser", E.getmessage (), e);}

 

The Android SDK has a built-in pull interpreter, which makes it easy to use xmlpullparser, and there are many different techniques for parsing XML files, such as sax and Dom, and more learning is needed.

More interested readers of Android-related content can view this site: "Android operating XML Data Skills Summary", "Android Programming activity Operation Tips Summary", "Android Resource Operation skills Summary", " Android File Operation Tips Summary, "Android operation SQLite Database Skills Summary", "Android operation JSON format Data Skills summary", "Android Database Operation skills Summary", "Android programming development of SD card operation method Summary", " Android Introduction and advanced tutorials, overview of the Android View view tips, and a summary of the usage of Android controls

I hope this article will help you with the Android program.

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.