gpt4 book ai didi

objective-c - 在 NSXMLParser 中解析 xml

转载 作者:可可西里 更新时间:2023-11-01 04:08:00 25 4
gpt4 key购买 nike

我已经阅读了许多关于如何从 xml 文件中获取文本的示例,但就是不知道如何操作。这是一个示例 xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<questions>
<set>
<question>Question</question>
<answer>Answer</answer>
</set>
</questions>

使用 -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI,获取值的最简单方法是什么问题Answer?我已经连接上了我的解析器代理和所有这些废话。

最佳答案

要实现 NSXMLParser,您需要实现它的委托(delegate)方法。

首先以这种方式启动NSXMLParser。

- (void)viewDidLoad {

[super viewDidLoad];

rssOutputData = [[NSMutableArray alloc]init];

//declare the object of allocated variable
NSData *xmlData=[[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:@""]];// 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];

//releasing the object of NSData as a part of memory management
[xmlData release];

}
//-------------------------------------------------------------


-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName
attributes: (NSDictionary *)attributeDict
{
if( [elementName isEqualToString:@"question"])
{

strquestion = [[NSMutableString alloc] init];

}
}


//-------------------------------------------------------------


-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
// init the ad hoc string with the value
currentElementValue = [[NSMutableString alloc] initWithString:string];
} else {
// append value to the ad hoc string
[currentElementValue appendString:string];
}
NSLog(@"Processing value for : %@", string);
}


//-------------------------------------------------------------


-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if( [elementName isEqualToString:@"question"])
{
[strquestion setString:elementName];
}

[currentElementValue release];
currentElementValue = nil;
}

上述委托(delegate)方法由解析器对象在遇到特定元素的结尾时发送给它的委托(delegate)。在此方法 didEndElement 中,您将获得 question 的值。

关于objective-c - 在 NSXMLParser 中解析 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8813968/

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