There are many ways to parse XML in IOS. Previously, I used gdataxml to parse XML files and explained how to use the XML parsing class provided by Google to parse XML files, today, we use another open-source project, kissxml, to parse XML files and introduce open-source projects and configuration items in the same way as in the previous article, download the source code from the kissxml source code and configure it as described in the previous article.
After the configuration is complete, introduce the following header file in appdelegate. m (I created an empty project). After compilation, it indicates that the project is successfully introduced and the configuration is ready for use immediately.
#import "DDXML.h"#import "DDXMLElementAdditions.h"
Kissxml supports XPath, which is very convenient to use. For instructions on XPath, refer to this article: XPath tutorial. Here we also use XPath for parsing.
Method In appdelegate. M:
-(Bool) Application :( uiapplication *) Application didfinishlaunchingwitexceptions :( nsdictionary *) launchoptions {self. window = [[uiwindow alloc] initwithframe: [[uiscreen mainscreen] bounds]; // override point for customization after application launch. self. window. backgroundcolor = [uicolor whitecolor]; [self. window makekeyandvisible]; // obtain the XML file nsstring * Path = [[nsbundle mainbundle] pathforresource: @ "users" oftype: @ "XML"] from the project directory; // obtain the nsdata object and start parsing nsdata * xmldata = [nsdata datawithcontentsoffile: path]; [self parsexml: xmldata]; return yes ;}
XML parsing method:
-(Void) parsexml :( nsdata *) Data {// document start (kissxml and gdataxml are also dom-based parsing methods) ddxmldocument * xmldoc = [[ddxmldocument alloc] initwithdata: data options: 0 error: Nil]; // use XPath to locate nodes (XPath is the positioning syntax in XML, similar to the SQL function in the database) nsarray * Users = [xmldoc nodesforxpath: @ "// user" error: Nil]; for (ddxmlelement * user in users) {nsstring * userid = [[user attributeforname: @ "ID"] stringvalue]; nslog (@ "User ID: % @", userid); ddxmlelement * nameele = [user elementforname: @ "name"]; If (nameele) {nslog (@ "User Name: % @ ", [nameele stringvalue]);} ddxmlelement * ageele = [user elementforname: @" Age "]; If (ageele) {nslog (@" user age: % @ ", [ageele stringvalue]) ;}}
The output result after compilation is as follows:
In this way, kissxml is used to parse XML files. Compared with gdataxml, kissxml improves the resolution speed, but the memory overhead is slightly higher. As the memory size of iOS devices increases, the resolution speed will be the first consideration.
To join our QQ group or public account, see: Ryan's
Zone public account and QQ Group
Welcome to my Sina Weibo chat: @ Tang Ren _ Ryan