gpt4 book ai didi

ios - 在 iOS 中使用 NSXML 解析数据

转载 作者:行者123 更新时间:2023-11-29 03:18:59 24 4
gpt4 key购买 nike

我正在尝试使用 NSXMLR 解析来自 Wordpress RSS 提要的数据。我的问题是导出已解析的数据。到目前为止,我有,

- (void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{

currentElement = [elementName copy];

if ([elementName isEqualToString:@"item"]){

currentTitle = [[NSMutableString alloc] init];
item = [[NSMutableDictionary alloc] init];
}

}

这门课

- (void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{


if ([elementName isEqualToString:@"item"]){
[item setObject:currentTitle forKey:@"title"];
}

[stories addObject:item];
}


- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{

if ([currentElement isEqualToString:@"title"]){
[currentTitle appendString:string];
}

}

NSMutableArray *故事;NSMutableDictionary *item;

所以在 ViewDidLoad 实现中,我有

//declare the object of allocated variable
NSData *xmlData=[[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:@"URL"]];// URL that given to parse.

//allocate memory for parser as well as
xmlParserObject =[[NSXMLParser alloc]initWithData:xmlData];
[xmlParserObject setDelegate:self];

//asking the xmlparser object to beggin with its parsing
[xmlParserObject parse];



NSLog(@"%@", [item objectForKey:@"title"]);

我的问题是我只打印一个对象,我有多个元素。我怎样才能让它扫描每一个并打印它们。

提前致谢。

最佳答案

如果我对你的代码理解正确,item 包含当前解析的项目,数组 stories 包含所有项目。

所以你必须先分配stories数组:

stories = [[NSMutableArray alloc] init];

然后你进行解析(但你应该添加错误检查):

NSData *xmlData=[[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:@"URL"]];
xmlParserObject =[[NSXMLParser alloc]initWithData:xmlData];
[xmlParserObject setDelegate:self];
if (![xmlParserObject parse]) {
// Parsing failed, report error...
}

最后打印数组的内容:

for (NSDictionary *story in stories) {
NSLog(@"%@", [story objectForKey:@"title"]);
}

didEndElement 方法可能应该如下所示:

- (void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:@"item"]){
[item setObject:currentTitle forKey:@"title"];
[stories addObject:item]; // <-- MOVED INTO THE IF-BLOCK
}
}

关于ios - 在 iOS 中使用 NSXML 解析数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21353425/

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