Android uses PULL to parse and generate XML files

Source: Internet
Author: User

 

Please kindly advise:

Email: weimingweicom@sina.com

Use PULL to parse and generate XML files:

On the Android platform, you can use Simple API for XML (SAX), Document Object Model (DOM), and the pull parser that comes with Android to parse XML files. The XML file to be parsed in this example is as follows:


File Name: csdn. xml

This file should be placed in the image directory:

 


<? Xml version = "1.0" encoding = "UTF-8"?>

<Persons>

<Person id = "23">

<Name> Li Ming </name>

<Age> 30 </age>

</Person>

<Person id = "20">

<Name> Li xiangmei </name>

<Age> 25 </age>

</Person>

</Persons>


The example defines a javabean to store the xml content parsed above. The javabean is Person. For the code, see the following remarks on this page:

Public class Person {

Private Integer id;

Private String name;

Private Short age;


Public Integer getId (){

Return id;

}

Public void setId (Integer id ){

This. id = id;

}

Public String getName (){

Return name;

}

Public void setName (String name ){

This. name = name;

}

Public Short getAge (){

Return age;

}

Public void setAge (Short age ){

This. age = age;

}

}


Layout effect:

 


Layout code:

<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android"

Xmlns: tools = "http://schemas.android.com/tools"

Android: layout_width = "match_parent"

Android: layout_height = "match_parent"

Android: paddingBottom = "@ dimen/activity_vertical_margin"

Android: paddingLeft = "@ dimen/activity_horizontal_margin"

Android: paddingRight = "@ dimen/activity_horizontal_margin"

Android: paddingTop = "@ dimen/activity_vertical_margin"

Tools: context = ". MainActivity">

<Button

Android: id = "@ + id/btn_pull"

Android: layout_width = "match_parent"

Android: layout_height = "wrap_content"

Android: text = "@ string/text_pull"/>

<Button

Android: id = "@ + id/btn_cpull"

Android: layout_width = "wrap_content"

Android: layout_height = "wrap_content"

Android: layout_alignLeft = "@ + id/btn_pull"

Android: layout_alignParentRight = "true"

Android: layout_below = "@ + id/btn_pull"

Android: layout_marginTop = "28dp"

Android: text = "@ string/btn_cxml"/>

</RelativeLayout>


Value code in String. xml:


<? Xml version = "1.0" encoding = "UTF-8"?>

<Resources>


<String name = "app_name"> AndoridPull parses and generates Xml files </string>

<String name = "action_settings"> Settings </string>

<String name = "text_pull"> Use pull to parse xml files </string>

<String name = "btn_cxml"> use the pull parser to generate an xml file </string>

</Resources>

 

Use the Pull parser to read XML files


In addition to using SAX and DOM to parse XML files, you can also use the Android built-in Pull parser to parse XML files. The Running Method of the Pull parser is similar to that of the SAX Parser. It provides similar events, such as the start element and end element events. You can use parser. next () to enter the next element and trigger the corresponding event. The event is sent as a numeric code, so you can use a switch to process the event you are interested in. When parsing an element, call parser. nextText () to obtain the value of the next Text element.


Use the Pull parser to read itcast. xml code.


 
Sometimes, we need to generate an XML file. There are many ways to generate an XML file. For example, we can use only one StringBuilder to group XML content and then write the content into the file; you can also use the pull parser to generate XML files by using DOM APIs. We recommend that you use the Pull parser.


Use the Pull parser to generate a myitcast. xml file with the same content as the itcast. xml file. The Code will be noted below this page


Use the following code to generate an XML file ):

File xmlFile = new File ("myitcast. xml ");

FileOutputStream outStream = new FileOutputStream (xmlFile );

OutputStreamWriter outStreamWriter = new OutputStreamWriter (outStream, "UTF-8 ");

BufferedWriter writer = new BufferedWriter (outStreamWriter );

WriteXML (persons, writer );

Writer. flush ();

Writer. close ();

If you only want to get the generated xml string content, you can use StringWriter:

StringWriter writer = new StringWriter ();

WriteXML (persons, writer );

String content = writer. toString ();


Code of the service layer when parsing xml files using Pull:


 

Package com. example. andorid04pullxml. service;


Import java. io. File;

Import java. io. FileNotFoundException;

Import java. io. FileOutputStream;

Import java. io. InputStream;

Import java. util. ArrayList;

Import java. util. List;


Import org. xmlpull. v1.XmlPullParser;

Import org. xmlpull. v1.XmlPullParserException;

Import org. xmlpull. v1.XmlSerializer;


Import android. OS. Environment;

Import android. util. Log;

Import android. util. Xml;


Import com. example. andorid04pullxml. domain. Person;


Public class PullXmlService {

Public Person currentPerson;


// Declare the return value

Public List <Person> readXML (InputStream is ){

List <Person> persons = null;

// Retrieve the parsing object using XML. newPullParser ()

XmlPullParser xmlPullParser = Xml. newPullParser ();

Try {// parse the file

XmlPullParser. setInput (is, "UTF-8 ");

// Obtain the parsed Event Type

Int eventType = xmlPullParser. getEventType ();

// Determine whether file resolution is complete

While (eventType! = XmlPullParser. END_DOCUMENT ){

Switch (eventType ){

Case XmlPullParser. START_DOCUMENT:

Persons = new ArrayList <Person> ();

Break;

Case XmlPullParser. START_TAG:

String tagName = xmlPullParser. getName ();

Log. v ("PullXmlService", tagName + "------");

// When the parsed tag is person

If ("person". equals (tagName )){

// Create a person object

CurrentPerson = new Person ();

// Set the id attribute to be converted

CurrentPerson. setId (Integer. parseInt (xmlPullParser

. GetAttributeValue (null, "id ")));

} Else if ("name". equals (tagName )){

CurrentPerson. setName (xmlPullParser. nextText ());

} Else if ("age". equals (tagName )){

CurrentPerson

. SetAge (new Short (xmlPullParser. nextText ()));

}

Break;

Case XmlPullParser. END_TAG:


If ("person". equals (xmlPullParser. getName ())

& CurrentPerson! = Null ){

// Add the person object to the set

Persons. add (currentPerson );

CurrentPerson = null;

}


Break;

}

// The next tag ID

EventType = xmlPullParser. next ();

}

// Close the stream

Is. close ();

} Catch (Exception e ){

// TODO Auto-generated catch block

E. printStackTrace ();

}

// Return

Return persons;

}

/**

* Use pull to generate XML files

* @ Param persons

* @ Return

*/

Public boolean write (List <Person> persons ){

// Implemented using pull resolution

If (Environment. getExternalStorageState (). equals (

Environment. MEDIA_MOUNTED )){

File sdCardDir = Environment. getExternalStorageDirectory ();

File file = new File (sdCardDir, "mycsdn. xml ");

XmlSerializer serializer = Xml. newSerializer ();

FileOutputStream fos = null;

Try {

// Create an output stream object of a file based on the file object

Fos = new FileOutputStream (file );

// Set the output stream and encoding.

Serializer. setOutput (fos, "UTF-8 ");

// Set the start of the file

Serializer. startDocument ("UTF-8", true );

// The persons label starts.

Serializer. startTag (null, "persons ");

For (Person person: persons ){

Serializer. startTag (null, "person ");

Serializer. attribute ("null", "id", person. getId () + "");

// Set the sub-Tag name of the person tag

Serializer. startTag (null, "name ");

Serializer. text (person. getName ());

Serializer. endTag (null, "name ");


// Set the age of the child tag of the person tag

Serializer. startTag (null, "age ");

Serializer. text (person. getAge () + "");

Serializer. endTag (null, "age ");


// End of the person tag

Serializer. endTag (null, "person ");

}

Serializer. endTag (null, "persons ");

Serializer. endDocument ();

Fos. flush ();

Fos. close ();

Return true;

} Catch (Exception e ){

// TODO Auto-generated catch block

E. printStackTrace ();

}

}

Return false;

}

}


The code in the most important MainActivity:


Package com. example. andorid04pullxml;


Import java. io. IOException;

Import java. util. List;


Import com. example. andorid04pullxml. domain. Person;

Import com. example. andorid04pullxml. service. PullXmlService;


Import android. OS. Bundle;

Import android. app. Activity;

Import android. view. Menu;

Import android. view. View;

Import android. widget. Button;

Import android. widget. Toast;


Public class MainActivity extends Activity {

// Pull parser Business Object

Public PullXmlService pullXmlService;

Public Button btn_pull, btn_cpull;

@ Override

Protected void onCreate (Bundle savedInstanceState ){

Super. onCreate (savedInstanceState );

// Set the displayed view

SetContentView (R. layout. activity_main );

PullXmlService = new PullXmlService ();

// Obtain the button Component Object

Btn_pull = (Button) findViewById (R. id. btn_pull );

Btn_cpull = (Button) findViewById (R. id. btn_cpull );

// Register an event

Btn_pull.setOnClickListener (new MyOnClickListener ());

Btn_cpull.setOnClickListener (new MyOnClickListener ());

}

 

@ Override

Public boolean onCreateOptionsMenu (Menu menu ){

// Inflate the menu; this adds items to the action bar if it is present.

GetMenuInflater (). inflate (R. menu. main, menu );

Return true;

}

Class MyOnClickListener implements View. OnClickListener {


@ Override

Public void onClick (View v ){

Int id = v. getId ();

Switch (id ){


Case R. id. btn_pull:

List <Person> persons = null;

Try {

Persons = pullXmlService. readXML (getAssets (). open ("csdn. xml "));

} Catch (IOException e ){

// TODO Auto-generated catch block

E. printStackTrace ();

}

If (persons! = Null ){

Toast. makeText (MainActivity. this, "parsing xml files using pull" + persons. get (0 ). getName () + "--" + persons. get (1 ). getName (),

Toast. LENGTH_LONG). show ();

}

Break;

Case R. id. btn_cpull:


Try {

List <Person> persons1 = pullXmlService. readXML (getAssets (). open ("csdn. xml "));

// Regenerate an xml file mycsdn. xml

Boolean flag = pullXmlService. write (persons1 );

If (flag ){

Toast. makeText (MainActivity. this, "the xml file is successfully parsed using pull ",

Toast. LENGTH_LONG). show ();

} Else {

Toast. makeText (MainActivity. this, "failed to generate xml file by pull Parsing ",

Toast. LENGTH_LONG). show ();


}

} Catch (IOException e ){

// TODO Auto-generated catch block

E. printStackTrace ();

}


Break;

Default:

Break;

}

}

}

 

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.