Parse XML files using Dom and Sax in IOS

Source: Internet
Author: User

XML parsing class in IOS: Click to open the link

There are two methods for parsing XML files in IOS: Dom and Sax. However, we recommend that you use the method recommended officially by Apple.

Sax parsing relies mainly on proxy methods. NSXMLParserDelegate

1) Prepare for sax parsing, configure the xml file, and set the delegate proxy


First, import the XML parsing class to the project, then add libxml2.dylib to the framework, and then set the path of the Header search Paths:

After setting these settings, create a UITextView and two buttons in the form of dragging the space in the attempt to controller the nib file and associate them with the method.

As follows: <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + pgltzybzcm9 "http://www.bkjia.com/uploadfile/Collfiles/20140102/2014010209553834.jpg" alt = "\">

The file to be parsed is as follows:


2013081205

Zhang San

HKUST iOS001

2013081206

Li Si

HKUST iOS001


Install a software on your computer, as shown in:


Otherwise, the parsing will fail.

I will share with you the code below:

HHLAppDelegate. h

#import 
 
  @class HHLViewController;@interface HHLAppDelegate : UIResponder 
  
   @property (strong, nonatomic) UIWindow *window;@property (strong, nonatomic) HHLViewController *viewController;@end
  
 

HHLAppDelegate. m

#import "HHLAppDelegate.h"#import "HHLViewController.h"@implementation HHLAppDelegate- (void)dealloc{    [_window release];    [_viewController release];    [super dealloc];}- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];    // Override point for customization after application launch.    self.viewController = [[[HHLViewController alloc] initWithNibName:@"HHLViewController" bundle:nil] autorelease];    self.window.rootViewController = self.viewController;    [self.window makeKeyAndVisible];    return YES;}- (void)applicationWillResignActive:(UIApplication *)application{    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.}- (void)applicationDidEnterBackground:(UIApplication *)application{    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.     // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.}- (void)applicationWillEnterForeground:(UIApplication *)application{    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.}- (void)applicationDidBecomeActive:(UIApplication *)application{    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.}- (void)applicationWillTerminate:(UIApplication *)application{    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.}@end


HHLViewController. h

# Import
 
  
// # Import
  @ Interface HHLViewController: UIViewController
  
   
// Display result @ property (retain, nonatomic) IBOutlet UITextView * ptextView; // @ property (retain, nonatomic) NSMutableString * mResultStr used to store resolution results; @ property (retain, nonatomic) NSMutableString * pTempStr; // Sax Parser @ property (retain, nonatomic) NSXMLParser * xmlParser;-(IBAction) btnDom :( id) sender;-(IBAction) btnSax :( id) sender; @ end
  
 


HHLViewController. m

# Import "HHLViewController. h "# import" GDataXMLNode. h "@ interface HHLViewController () @ end @ implementation HHLViewController-(void) dealloc {[_ ptextView release]; [_ xmlParser release]; [super dealloc];}-(id) initWithNibName :( NSString *) nibNameOrNil bundle :( NSBundle *) handle {self = [super initWithNibName: nibNameOrNil bundle: role]; if (self) {// Custom initialization} return self ;} -(void) viewDidLoad {[super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. // self. mResultStr = [[[NSMutableString alloc] init] autorelease];}-(IBAction) btnDom :( id) sender {// NSError * error; // obtain the file path NSString * path = [[NSBundle mainBundle] pathForResource: @ "student" ofType: @ "xml"]; // locate the string through the path (note the encoding method) NSString * xmlString = [[NSString alloc] initWithContentsOfFile: path encoding: NSUTF8StringEncoding error: nil]; // NSLog (@ "xml = % @", xmlString ); // pass the data to the parser for parsing GDataXMLDocument * pXMLDocument = [[GDataXMLDocument alloc] initWithXMLString: xmlString options: 0 error: nil]; // defines an object for storing the result, start from the root element and save GDataXMLElement * pRootElement = [pXMLDocument rootElement]; // locate all the elements whose label name is student and save it to the array. // locate the related elements based on the keyword, (return value is an array) NSArray * pArr = [pRootElement elementsForName: @ "student"]; NSLog (@ "pArr = % @", pArr ); // traverse all elements whose keywords are student NSMutableString * pStr = [[NSMutableString alloc] init]; [pStr appendFormat: @ "Start parsing XML of Dom file \ n"]; for (int I = 0; I <[pArr count]; I ++) {GDataXMLNode * node = [pArr objectAtIndex: I]; [pStr appendFormat: @ "****************** student ****************** \ n" ]; for (int j = 0; j <[node childCount]; j ++) {GDataXMLNode * sub_Node = [node childAtIndex: j]; switch (j) {case 0: [pStr appendFormat: @ "stu_num = % @ \ n", [sub_Node stringValue]; break; case 1: [pStr appendFormat: @ "stu_name = % @ \ n ", [sub_Node stringValue]; break; case 2: [pStr appendFormat: @ "stu_class = % @ \ n", [sub_Node stringValue]; break; default: break ;}}} [pStr appendFormat: @ "***************** student **************** \ n"]; [pStr appendFormat: @ "Resolution completed"]; self. ptextView. text = pStr; [pStr release];}-(IBAction) btnSax :( id) sender {NSString * path = [[NSBundle mainBundle] pathForResource: @ "student" ofType: @ "xml"]; NSData * pData = [[NSData alloc] initWithContentsOfFile: path]; // initialize the parser self. xmlParser = [[NSXMLParser alloc] initWithData: pData]; // sets the delegate object self. xmlParser. delegate = self; // variable string initialization self. mResultStr = [[NSMutableString alloc] init]; self. pTempStr = [[NSMutableString alloc] init]; // start parsing. If YES is returned successfully, no bool flag = [self. xmlParser parse]; if (flag) {[self. mResultStr appendFormat: @ "% @ \ r \ n", @ "resolution successful"]; NSLog (@ "resolution successful");} else {[self. mResultStr appendFormat: @ "% @ \ r \ n", @ "resolution failed"]; NSLog (@ "resolution failed ");}} # pragma mark ------------------- NSXMLParserDelegate --------- // resolution document start-(void) parserDidStartDocument :( NSXMLParser *) parser {NSLog (@ "document start"); [self. mResultStr appendFormat: @ "% @ \ r \ n", @ "Start parsing the XML of SAX file"]; [self. mResultStr appendFormat: @ "% @ \ r \ n ", @ "************* student ****************"];} // callback when data is encountered, including space and carriage return-(void) parser :( NSXMLParser *) parser foundCharacters :( NSString *) string {NSLog (@ "文""); [self. pTempStr setString: @ ""]; // The string parameter indicates the received data [self. pTempStr appendFormat: @ "% @", string]; NSLog (@ "string = % @", self. pTempStr);} // call-(void) parser :( NSXMLParser *) parser didStartElement :( NSString *) elementName namespaceURI :( NSString *) namespaceURI qualifiedName :( NSString *) qName attributes :( NSDictionary *) attributeDict {NSLog (@ "tag start");} // call the end Of the tag-(void) parser :( NSXMLParser *) parser didEndElement :( NSString *) elementName namespaceURI :( NSString *) namespaceURI qualifiedName :( NSString *) qName {NSLog (@ "tag end"); // determine the end tag (the elementName parameter is the tag name) if (NSOrderedSame = [elementName compare: @ "student"]) {[self. mResultStr appendFormat: @ "% @ \ n ", @ "************** student *****************"];} else if (NSOrderedSame = [elementName compare: @ "student_list"]) {[self. mResultStr appendFormat: @ "% @ \ r \ n", @ "Resolution completed"];} else {[self. mResultStr appendFormat: @ "% =%@ \ r \ n", elementName, self. pTempStr] ;}}- (void) parserDidEndDocument :( NSXMLParser *) parser {self. ptextView. text = self. mResultStr; [_ mResultStr release]; [_ pTempStr release];}-(void) didReceiveMemoryWarning {[super didreceivemorywarning]; // Dispose of any resources that can be recreated .} @ end


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.