There are many ways to parse XML, which can be parsed with dom,sax, but the most commonly used on Android is pull parsing, and here's a simple example
<?xmlversion= "1.0" encoding= "UTF-8"?><persons> <person id= "Up" > <name>allen</ name> <age>36</age> </person> <person id= > <name>james< /name> <age>25</age> </person></persons>
JavaBean class
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 {this.age = age;}}
Generating an XML file
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 (); return writer.tostring (); } catch (Exception e) {e.printstacktrace (); } return null;}
Parsing XML files
public static list<person> ReadXML (InputStream instream) {xmlpullparser parser = Xml.newpullparser (); try { 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 it is followed by a text node, it returns 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;} catch (Exception e) {e.printstacktrace ();} return null;}
,
Using pull to generate and parse XML files