How to Use the pull parser to operate xml files in Android

Source: Internet
Author: User

I. Use the Pull parser to read XML files

In addition to using SAX or DOM to parse XML files, you can also use the Android built-in Pull parser to parse XML files. The Pull parser is an open-source java project that can be used for both android and JavaEE. If it is used in javaEE, you need to put its jar file into the class path. Because Android has already been integrated into the Pull parser, no jar file needs to be added. Xml files used by the android system are parsed using the Pull parser. 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. Unlike SAX, the events generated by the Pull parser are numbers rather than methods. Therefore, you can use a switch to process events of interest. When parsing an element, call parser. nextText () to obtain the value of the next Text node.

Ii. Use the Pull parser to generate an XML file

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 use the dom api to generate an XML file, or use the pull parser to generate an XML file,We recommend that you use the Pull parser.

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

Use the following code to generate an XML file ):

File xmlFile = new File ("myljq. 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 ();

Case:

123. xml

Copy codeThe Code is as follows: <? Xml version = '1. 0' encoding = 'utf-8' standalone = 'Yes'?>
<Persons>
<Person id = "1">
<Name> zhangsan </name>
<Age> 12 </age>
</Person>
<Person id = "2">
<Name> lisi </name>
<Age> 34 </age>
</Person>
</Persons>

PullPersonService pull parser operation class
Copy codeThe Code is as follows: package com. ljq. service;

Import java. io. InputStream;
Import java. io. Writer;
Import java. util. ArrayList;
Import java. util. List;

Import org. xmlpull. v1.XmlPullParser;
Import org. xmlpull. v1.XmlSerializer;

Import com. ljq. entity. Person;

Import android. util. Xml;

/**
* Pull parses xml files
*
* @ Author jiqinlin
*
*/
Public class PullPersonService {

/**
* Use the pull parser to generate an xml file
*
* @ Param persons
* @ Param writer
* @ Return
*/
Public static String writeXML (List <Person> persons, Writer writer ){
XmlSerializer serializer = Xml. newSerializer ();
Try {
Serializer. setOutput (writer );
Serializer. startDocument ("UTF-8", true );
// The first parameter is the namespace. If the namespace is not used, you can set it to null.
Serializer. startTag ("", "persons ");
For (Person person: persons ){
Serializer. startTag ("", "person ");
Serializer. attribute ("", "id", person. getId (). toString ());
Serializer. startTag ("", "name ");
Serializer. text (person. getName ());
Serializer. endTag ("", "name ");
Serializer. startTag ("", "age ");
Serializer. text (person. getAge (). toString ());
Serializer. endTag ("", "age ");
Serializer. endTag ("", "person ");
}
Serializer. endTag ("", "persons ");
Serializer. endDocument ();
} Catch (Exception e ){
E. printStackTrace ();
}
Return writer. toString ();
}

/**
* Use the pull parser to parse xml files
*
* @ Param inStream
* @ Return
* @ Throws Exception
*/
Public static List <Person> readXML (InputStream inStream) throws Exception {
XmlPullParser parser = Xml. newPullParser ();
Parser. setInput (inStream, "UTF-8 ");
Int eventType = parser. getEventType ();
Person currentPerson = null;
List <Person> persons = null;
While (eventType! = XmlPullParser. END_DOCUMENT ){
Switch (eventType ){
Case XmlPullParser. START_DOCUMENT: // document start event. Data initialization can be performed.
Persons = new ArrayList <Person> ();
Break;
Case XmlPullParser. START_TAG: // start element event
String name = parser. getName ();
If (name. inclusignorecase ("person ")){
CurrentPerson = new Person ();
CurrentPerson. setId (new Integer (parser. getAttributeValue (null, "id ")));
} Else if (currentPerson! = Null ){
If (name. inclusignorecase ("name ")){
CurrentPerson. setName (parser. nextText (); // if it is followed by a Text element, its value is returned.
} Else if (name. Your signorecase ("age ")){
CurrentPerson. setAge (new Short (parser. nextText ()));
}
}
Break;
Case XmlPullParser. END_TAG: // End Element event
If (parser. getName (). inclusignorecase ("person") & currentPerson! = Null ){
Persons. add (currentPerson );
CurrentPerson = null;
}
Break;
}
EventType = parser. next ();
}
InStream. close ();
Return persons;
}

}

PullPersonServiceTest pull parser test class
Copy codeThe Code is as follows: package com. ljq. test;

Import java. io. BufferedWriter;
Import java. io. FileOutputStream;
Import java. io. InputStream;
Import java. io. OutputStreamWriter;
Import java. util. ArrayList;
Import java. util. List;

Import com. ljq. entity. Person;
Import com. ljq. service. PullPersonService;

Import android. content. Context;
Import android. test. AndroidTestCase;
Import android. util. Log;

Public class PullPersonServiceTest extends AndroidTestCase {
Private final String TAG = "PullPersonServiceTest ";
/**
* Use the pull parser to parse xml files
*
* @ Throws Exception
*/
Public void testReadXML () throws Exception {
// InputStream inputStream = PullPersonServiceTest. class. getClassLoader (). getResourceAsStream ("ljq. xml ");
InputStream inputStream = this. getContext (). openFileInput ("123.xml ");
List <Person> persons = PullPersonService. readXML (inputStream );
For (Person person: persons ){
Log. I (TAG, person. getId () + ":" + person. getName () + ":" + person. getAge ());
}
}

/**
* Use the pull parser to generate an xml file
*
* @ Throws Exception
*/
Public void testWriteXml () throws Exception {
FileOutputStream fileOutputStream = this. getContext (). openFileOutput ("123.xml", Context. MODE_PRIVATE );
OutputStreamWriter outStreamWriter = new OutputStreamWriter (fileOutputStream, "UTF-8 ");
List <Person> persons = new ArrayList <Person> ();
Persons. add (new Person (1, "zhangsan", (short) 12 ));
Persons. add (new Person (2, "lisi", (short) 34 ));
BufferedWriter writer = new BufferedWriter (outStreamWriter );
String string = PullPersonService. writeXML (persons, writer );
Log. I (TAG, string. toString ());
}
}

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.