NSXMLParser在iPhone上,我如何使用它给定一个xml文件(newb here:\) [英] NSXMLParser on the iPhone, how do i use it given a xml file (newb here :\)
问题描述
我想知道如何使用NSXML解析器。
所以让我说一个简单的xml文件中包含元素
1/1/1000
14:15:16
Hey guys, was wondering how do i use the NSXML parser. so lets say given i have a simple xml file with elements like 1/1/1000 14:15:16
我如何使用NSXMLParser解析XML文件(在本地btw,桌面上),检查每个元素,并将它们存储在一个数组中,以便以后显示/使用?
How could i use the NSXMLParser to parse the XML File(Its on locally btw, desktop), check through each element and store each of them in an array either to be displayed/used later?
我正在查找一些关于它的文档,我绝对不知道如何使用解析器
i知道有3种方法(或更多,请更正我如果错误的话)可以重写
- .. etc didStartElement
- .. etc didEndElement
- .. etc foundCharacters
I was looking through some documentation about it and i absolutely have no idea on how to use the parser i know that there are 3 methods(or more ,please correct me if im wrong) that can be overridden -..etc didStartElement -..etc didEndElement -..etc foundCharacters
推荐答案
最简单的做法是这样做:
The simplest thing is to do something like this:
NSXMLParser *xmlParser = [[NSXMLParser alloc]initWithData:<yourNSData>];
[xmlParser setDelegate:self];
[xmlParser parse];
请注意,setDelegate:将委托设置为'self',意味着当前对象。因此,在该对象中,您需要实现您在问题中提及的委托方法。
Notice that setDelegate: is setting the delegate to 'self', meaning the current object. So, in that object you need to implement the delegate methods you mention in the question.
在代码中进一步下拉,粘贴:
so further down in your code, paste in:
- (void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict{
NSLog(@"I just found a start tag for %@",elementName);
if ([elementName isEqualToString:@"employee"]){
// then the parser has just seen an <employee> opening tag
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
NSLog(@"the parser just found this text in a tag:%@",string);
}
等等。
当你想做一些事情时,比如将一个变量设置为某个标签的值有点困难,但是通常使用类变量caleld来完成, didStartElement
:方法中设置为true(YES)的 BOOL inEmployeeTag
c> didEndElement :method - 然后检查 foundCharacters
方法中的值。
It's a little harder when you want to do something like set a variable to the value of some tag, but generally it's done using a class variable caleld something like "BOOL inEmployeeTag
" which you set to true (YES) in the didStartElement
: method and false in the didEndElement
: method - and then check for it's value in the foundCharacters
method. If it's yes, then you assign the var to the value of string, and if not you don't.
richard
这篇关于NSXMLParser在iPhone上,我如何使用它给定一个xml文件(newb here:\)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!