The solution to using the pull parser to manipulate XML files in Android _android

Source: Internet
Author: User

First, 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 Java EE. If you need to put the jar file into the classpath with Java EE, because Android is already integrated into the pull parser, you don't need to add any jar files. The various XML files used by the Android system itself are parsed using the pull parser. The pull parser runs the same way as the SAX parser. It provides similar events, such as start and end element events, using Parser.next () to enter the next element and trigger the corresponding event. Unlike sax, the event generated by the pull parser is a number, not a method, so you can use a switch to handle events of interest. When the element begins parsing, the Parser.nexttext () method is invoked to get the value of the next text type node

Ii. using the pull parser to generate XML files

Sometimes, we need to generate an XML file, there are many ways to generate XML files, such as: You can use only one StringBuilder group to spell XML content, and then write the content to the file, or use the DOM API to generate XML files, Alternatively, you can use the pull parser to generate an XML file, which is recommended here for you to use the pull parser.

Use the pull parser to generate a myljq.xml file with the same content as the Ljq.xml file, with the code below the note

Use the following code (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 Code code 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 Code code 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 Parse XML file
*
* @author Jiqinlin
*
*/
public class Pullpersonservice {

/**
* Using the pull parser to generate XML files
*
* @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 a namespace, and if you do not use a namespace, 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 ();
}

/**
* Parse XML file with pull parser
*
* @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 processed
persons = new arraylist<person> ();
Break
Case xmlpullparser.start_tag://Start Element event
String name = Parser.getname ();
if (Name.equalsignorecase ("person")) {
Currentperson = new Person ();
Currentperson.setid (New Integer (Parser.getattributevalue (NULL, "id"));
else if (Currentperson!= null) {
if (name.equalsignorecase ("name")) {
Currentperson.setname (Parser.nexttext ());//If followed by the text element, return its value
else if (name.equalsignorecase ("Age")) {
Currentperson.setage (New Short (Parser.nexttext ()));
}
}
Break
Case xmlpullparser.end_tag://End Element Event
if (Parser.getname (). Equalsignorecase ("person") && Currentperson!= null) {
Persons.add (Currentperson);
Currentperson = null;
}
Break
}
EventType = Parser.next ();
}
Instream.close ();
return persons;
}

}


pullpersonservicetest Pull Parser test class
Copy Code code 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";
/**
* Parse XML file with pull parser
*
* @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 ());
}
}

/**
* Using the pull parser to generate XML files
*
* @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 ());
}
}

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.