Import Java.io.InputStream;
Import Java.io.OutputStream;
Import java.util.ArrayList;
Import java.util.List;
Import Org.xmlpull.v1.XmlPullParser;
Import Org.xmlpull.v1.XmlSerializer;
Import Android.annotation.SuppressLint;
Import android.util.Xml;
Import Com.example.domain.Person;
/**
* @author Wesley
* @version
* @date January 26, 2015 11:32:09
*
*/
public class Xmlservice {
/**
* Read data
* @param the data to be read by XML
* @return
* @throws Exception
*/
@SuppressLint ("usevalueof")
public static list<person> readXml (InputStream xml) throws exception{
list<person> persons = NULL;
person person = null;
//Create a pull instance
Xmlpullparser pullparser = Xml.newpullparser ();
//Set the XML data to be parsed for the pull parser
pullparser.setinput (XML, "UTF-8");
//Get the first event
int event = Pullparser.geteventtype ();
//Determine if document End event is not
while (event! = xmlpullparser.end_document) {
Switch (event) {
Case Xmlpullparser.start_document:
persons = new arraylist<person> ();
break;
Case Xmlpullparser.start_tag:
if ("Person". Equals (Pullparser.getname ())) {
int id = new Integer (pullparser.getattributevalue (0));
person = new person ();
Person.setid (ID);
}
if ("Name". Equals (Pullparser.getname ())) {
String name = Pullparser.nexttext ();
person.setname (name);
}
if ("Age". Equals (Pullparser.getname ())) {
int age = new Integer (Pullparser.nexttext ());
person.setage (age);
}
break;
Case Xmlpullparser.end_tag:
if ("Person". Equals (Pullparser.getname ())) {
Persons.add (person);
person = null;
}
break;
}
event = Pullparser.next ();
}
return persons;
}
/**
* Save data
* @param persons data
* @param out input direction
* @throws Exception
*/
public static void SaveXML (List<person> persons,outputstream out) throws exception{
//Create a serialized instance
XmlSerializer serializer = Xml.newserializer ();
//Set output stream
Serializer.setoutput (out, "UTF-8");
//Setup Document
serializer.startdocument ("UTF-8", true);
//Set Start tab
Serializer.starttag (NULL, "persons");
for (person person:persons) {
Serializer.starttag (null, "person");
serializer.attribute (NULL, "id", Person.getid (). toString ());
Serializer.starttag (null, "name");
Serializer.text (Person.getname ());
Serializer.endtag (null, "name");
Serializer.starttag (null, "age");
Serializer.text (Person.getage (). toString ());
Serializer.endtag (null, "age");
Serializer.endtag (null, "person");
}
//Create end tag
Serializer.endtag (NULL, "persons");
//End Document
serializer.enddocument ();
Out.flush ();
out.close ();
}
}
Android Series III (parse XML file using Pull method)