For example, say you have a simple XML file such as the following:
<?xml version= "1.0" encoding="UTF8"> |
<article author="John Doe"> |
<para>This is a very short article.</para> |
</article> |
The parser would report the following series of events to its delegate:
Started parsing document
Found start tag for element article
---<article >
Found attribute author
of element article
, value “John Doe”-----author="John Doe"
Found start tag for element para -----
<para>
Found characters ------This is a very short article. 【
element's value】
Found end tag for element para
------</para>
Found end tag for element article----
</article>
Ended parsing document
使用NSXMLParser步骤方法如下:
步骤一,确定从xml文件解析出来的数据如何保存--定义一个类(结构体)
小提示:可能一个xml文件解析出的数据包含多个对象,可以用NSMutableArray来保存。如参考一中提到的books
步骤二,
自定义解析处理方法(主要三个方法)--
Delegate代理
为了使代码清晰 可以单独提出来作为一个类
方法一:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict {
if([elementName isEqualToString:@"Books"]) {
//Initialize the array.
appDelegate.books = [[NSMutableArray alloc] init];
}
aBook.bookID = [[attributeDict objectForKey:@"id"] integerValue];
}
方法二:主要处理
element's value 主要一般都是如下处理保存
value值到字符串
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if(!currentElementValue)
currentElementValue = [[NSMutableString alloc] initWithString:string];
else
[currentElementValue appendString:string];
NSLog(@"Processing Value: %@", currentElementValue);
}
方法三:
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if([elementName isEqualToString:@"Book"]) {
[appDelegate.books addObject:aBook];
[aBook release];
aBook = nil;
}
}
步骤三 获取xml文件,并建立
NSXMLParser对象,后
解析
如参考一中实例,从url获取xml文件,并实例化NSXMLParser对象
NSURL *url = [[NSURL alloc] initWithString:@"http://sites.google.com/site/iphonesdktutorials/xml/Books.xml"];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
//Initialize the delegate.实例化解析处理方法的代理(步骤二中定义的代理)
XMLParser *parser = [[XMLParser alloc] initXMLParser];
//Set delegate 设置NSXMLParser对象的解析方法代理
[xmlParser setDelegate:parser];
//Start parsing the XML file.调用代理解析NSXMLParser对象
BOOL success = [xmlParser parse];
if(success)
NSLog(@"No Errors");
else
NSLog(@"Error Error Error!!!");