Add a xml file in your project
XML File - myxml.xml
<?xml version="1.0" encoding="utf-8" ?>
<data>
<object>
<name>English</name>
<age>24</age>
</object>
<object>
<name>Akram</name>
<age>20</age>
</object>
<object>
<name>John</name>
<age>30</age>
</object>
</data>
Code of file XMLParser.h
#import <UIKit/UIKit.h>
@interface XMLParser : NSObject {
NSMutableString *currentElementValue;
NSMutableArray *records;
NSMutableDictionary *data;
}
-(void)parseDataWithCase;
-(NSMutableArray *)records;
@end
Code of file XMLParser.m
#import "XMLParser.h"
@implementation XMLParser
-(void)parseDataWithCase{
NSString *filePath = @"myxml.xml";
// initializing array to be obtained after parsing
if(records)
[records removeAllObjects];
else
records=[[NSMutableArray alloc] init];
// xml parsing
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:[NSData dataWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:filePath]]];
[parser setDelegate:self];
[parser setShouldResolveExternalEntities:YES];
BOOL success;
success = [parser parse]; // return value not used
[parser release];
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
}
- (void)parser:(NSXMLParser*)parser foundCharacters:(NSString*)string{
currentElementValue = [[NSString alloc] initWithString:string];
if( [currentElementValue isEqualToString:@"\n"] || [currentElementValue isEqualToString:@"NULL"] || [currentElementValue isEqualToString:@"(null)"] ){
[currentElementValue release];
}
}
- (void)parser:(NSXMLParser*)parser didEndElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qName{
if ([elementName isEqualToString:@"data"]){
[data removeAllObjects];
} else if ([elementName isEqualToString:@"object"]){
[records addObject:[[data mutableCopy] autorelease]];
[data removeAllObjects];
} else {
if(data){
}else{
data=[[NSMutableDictionary alloc] initWithCapacity:2];
}
[data setObject:currentElementValue forKey:elementName];
[currentElementValue release];
}
}
-(NSMutableArray *)records{
return records;
}
- (void) dealloc {
[records release];
[data release];
[super dealloc];
}
@end
import the XMLParser.h class in your class
Call the function parseDataWithCase for parsing xml
and then call the records it return a array of that xml.
XMLParser *xmlParser = [[XMLParser alloc] init];
[xmlParser parseDataWithCase];
myArray = [xmlParser records];
[xmlParser release];
(
{
name = "Amit";
age = 24;
},
{
name = "Akram";
age = 20;
},
{
name = "John";
age = 30;
},
)
You can customize your parse method as you own need
- (void)parser:(NSXMLParser*)parser didEndElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qName