GDataXMLParser是一個對xml具有良好操作的第三方庫。解析的方法如下:
步驟:
一、下載GDataXMLParser庫,把解壓後Source/XMLSupport/下的兩個檔案:GDataXMLNode.h和GDataXMLNode.m拖到工程中。
一、加入libxml2.dylib架構。
二、設定Search Paths中Header Search Paths為/usr/include/libxml2。
三、在檔案中匯入標頭檔:GDataXMLNode.h。
四、建立dom結構。
Objective-c代碼
- NSData *xmlData = [[NSMutableData alloc] initWithContentsOfFile:@"test.xml"];
- NSError *error;
- GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&error];
五、基於xpath的解析。
Objective-c代碼
- NSArray *themeAttr = [doc nodesForXPath:@"//theme" error:&error];
- for(GDataXMLElement *themeElement in themeAttr){
- GDataXMLNode *themeIDNode = [themeElement attributeForName:@"id"];//解析屬性
- int themeID = [themeIDNode.stringValue intValue];//數字
-
- //theme url
- GDataXMLNode *themeURLNode = [themeElement attributeForName:@"url"];//字串
- NSString *themeURL = themeURLNode.stringValue;
- }