First, Friendbean.
PackageCom.example.other; Public classfriendbean{PrivateString FName =NULL; PrivateString fimg =NULL; Private intIID =-1; PublicString Getfname () {returnFName; } Public voidsetfname (String fName) {fName=FName; } PublicString getfimg () {returnfimg; } Public voidsetfimg (String fimg) {fimg=fimg; } Public intGetID () {returnIID; } Public voidSetID (intiId) { This. IID =iId; } }
Then create a new class Friendxmlcontenthandler, using Sax to parse the XML
PackageCom.example.other;Importjava.util.ArrayList;Importjava.util.List;Importorg.xml.sax.Attributes;Importorg.xml.sax.SAXException;ImportOrg.xml.sax.helpers.DefaultHandler;/** * Parse the following XML * <friend id= "1" > * <fname></fname> * <fimg></fimg> * </friend> * &L T;friend> .... * * * Use: * public static list<friend> ReadXML (InputStream instream) * {* try {* Create parser * SAXParserFactory SPF = saxparserfactory.newinstance (); * SAXParser SAXParser = Spf.newsaxparser (); *//Set the correlation property of the parser, true indicates that the namespace attribute is turned on * saxparser.setproperty ("http://xml.org/sax/features/namespaces", true); * Xmlcontenthandler handler = new Xmlcontenthandler (); * Saxparser.parse (instream, handler); * Instream.close (); * return Handler.getallfriends (); *} * catch (Exception e) * {* E.printstacktrace (); *} * return null; *} * * */ Public classFriendxmlcontenthandlerextendsdefaulthandler{PrivateList<friendbean> m_lfriends =NULL; PrivateFriendbean M_currentfriend =NULL;//record Current Object PrivateString M_tagname =NULL;//currently parsed element label PublicList<friendbean>getallfriends () {returnM_lfriends; } //get started with a document@Override Public voidStartdocument ()throwssaxexception {//TODO auto-generated Method StubM_lfriends =NewArraylist<friendbean>(); Super. Startdocument (); } //Start parsing@Override Public voidstartelement (String uri, String localname, String qName, Attributes Attributes)throwssaxexception {//TODO auto-generated Method Stub if(Localname.equals ("friend") ) {M_currentfriend=NewFriendbean (); M_currentfriend.setid (Integer.parseint (Attributes.getvalue ("id"))); } This. M_tagname =LocalName; } //Enter friend inside@Override Public voidCharacters (Char[] ch,intStartintlength)throwssaxexception {//TODO auto-generated Method Stub if(M_tagname! =NULL) {String data=NewString (CH, start, length); if(M_tagname.equals ("FName") ) { This. M_currentfriend.setfname (data); } Else if(M_tagname.equals ("Fimg") ) { This. m_currentfriend.setfimg (data); } } } //@Override Public voidendElement (String uri, String localname, string qName)throwssaxexception {//TODO auto-generated Method Stub if(Localname.equals ("friend") {m_lfriends.add (m_currentfriend); M_currentfriend=NULL; } This. M_tagname =NULL; }}
ANDROID_ Friend list XML parsing constructs