首先添加libxml2.dylib到工程中,再导入头文件,#include <libxml/xmlreader.h>
再加入如下代码:
-(NSMutableArray*)parser:(NSString*)xmlStr{
//解析xml
NSData *xmlData = [xmlStr dataUsingEncoding:NSUTF8StringEncoding];
xmlTextReaderPtr reader = xmlReaderForMemory([xmlData bytes],
[xmlData length],
NULL, nil,
(XML_PARSE_NOBLANKS | XML_PARSE_NOCDATA | XML_PARSE_NOERROR | XML_PARSE_NOWARNING));
if (!reader) {
NSLog(@"Failed to load xmlreader");
return;
}
NSString *currentTagName = nil;
NSDictionary *currentPerson = nil;
NSString *currentTagValue = nil;
NSMutableArray *advertiseMArray = [NSMutableArray array];
char* temp;
while (true) {
if (!xmlTextReaderRead(reader)) break;
switch (xmlTextReaderNodeType(reader)) {
case XML_READER_TYPE_ELEMENT:
// starting an element
temp = (char*)xmlTextReaderConstName(reader);
currentTagName = [NSString stringWithCString:temp
encoding:NSUTF8StringEncoding];
if ([currentTagName isEqualToString:@"元素信息"]) {
currentPerson = [NSMutableDictionary dictionary];
[advertiseMArray addObject:currentPerson];
}
continue;
case XML_READER_TYPE_TEXT:
//The current tag has a text value, stick it into the current
temp = (char*)xmlTextReaderConstValue(reader);
currentTagValue = [NSString stringWithCString:temp
encoding:NSUTF8StringEncoding];
if (!currentPerson) return;
[currentPerson setValue:currentTagValue forKey:currentTagName];
currentTagValue = nil;
currentTagName = nil;
default: continue;
}
}
// NSLog(@"%@:%s Final data: %@", [self class], _cmd, advertiseMArray );
return advertiseMArray;
}
这里返回的是一个mutableArray类型的。