我正在尝试解析一些XML数据并将解析后的数据附加到NSString对象中。我已经使用NSXMLParser成功解析了XML数据,但是当我记录名为arrayString
的字符串的值时,我只得到第一个<name>
的值,而不是所有值。我做错了什么?
这是我的代码:
(void)parseWithData:(NSData *)data {
parser = [[NSXMLParser alloc] initWithData:data];
[parser setDelegate:self];
//You might want to consider additional params like:
[parser setShouldProcessNamespaces:NO];
[parser setShouldReportNamespacePrefixes:NO];
[parser setShouldResolveExternalEntities:NO];
//And then finally (which activates the delegates):
[parser parse];
NSLog(@"The content of the array is%@",childElement);
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
currentElement = nil;
currentElement = [elementName copy];
if ([elementName isEqualToString:@"row"]) {
//This means the parser has entered the XML parent element named: xmlParentElement
//All of the child elements that need to be stored in the array should have their own IVARs and declarations.
childElement = [[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
//For all child elements, run this if statement.
if ([currentElement isEqualToString:@"name"]) {
[childElement appendString:string];
NSLog(string);
[arrayString stringByAppendingString:string];
// NSLog(arrayString);
}
我通过调用这些方法解析数据:
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];
[self parseWithData:data];
答案 0 :(得分:1)
stringByAppendingString
函数返回NSString
。它不会改变接收器。
您需要修复stringByAppendingString
的使用。例如,在foundCharacters
中,将其替换为:
[arrayString stringByAppendingString:string];
有了这个:
arrayString = [arrayString stringByAppendingString:string];
Apple的documentation on stringByAppendingString
:
stringByAppendingString:
返回通过将给定字符串附加到接收器而生成的新字符串。
此外,在追加字符串时,不要忘记在追加字符串之前初始化字符串。
答案 1 :(得分:1)
我认为stringByAppendingString方法创建了一个新的NSString。试试这个而不是:
arrayString = [arrayString stringByAppendingString:string];