gpt4 book ai didi

ios - Objective-C 追加到字符串不工作 NSXMLParser

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:12:00 24 4
gpt4 key购买 nike

我正在尝试解析一些 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];

最佳答案

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

您需要修复对 stringByAppendingString 的使用。例如,在 foundCharacters 中,替换为:

[arrayString stringByAppendingString:string];

有了这个:

arrayString = [arrayString stringByAppendingString:string];

Apple 的 documentation on stringByAppendingString :

stringByAppendingString:

Returns a new string made by appending a given string to the receiver.

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

关于ios - Objective-C 追加到字符串不工作 NSXMLParser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17996256/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com