2

我正在尝试解析一些 XML 数据并将解析后的数据附加到 NSString 对象中。我已经使用 NSXMLParser 成功解析了 XML 数据,但是当我记录名为 的字符串的值时arrayString,我只得到了 first 的值<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];
4

2 回答 2

1

stringByAppendingString函数返回一个NSString. 它不会改变接收器。

您需要修复对stringByAppendingString. 例如,在 中foundCharacters,替换为:

[arrayString stringByAppendingString:string];

有了这个:

arrayString = [arrayString stringByAppendingString:string];

苹果的文档stringByAppendingString

stringByAppendingString:

返回通过将给定字符串附加到接收器而生成的新字符串。

此外,在追加字符串时,不要忘记在追加之前初始化字符串。

于 2013-08-01T14:40:07.427 回答
1

我认为 stringByAppendingString 方法创建了一个新的 NSString。试试这个而不是那个:

arrayString = [arrayString stringByAppendingString:string];
于 2013-08-01T14:43:22.443 回答