问题描述
我想知道如何使用NSXML解析器。
所以可以说,假设我有一个简单的xml文件,其元素如下:
I was wondering how do I use the NSXML parser.so lets say given I have a simple xml file with elements like:
<Today>
<Date>1/1/1000</Date>
<Time>14:15:16</Time>
</Today>
如何使用NSXMLParser解析XML文件(位于本地btw,桌面),检查通过每个元素并将它们每个存储在一个数组中以供以后显示/使用?
How could I use the NSXMLParser to parse the XML File (It's on locally btw, desktop), check through each element and store each of them in an array either to be displayed/used later?
我正在浏览有关它的一些文档,但我不知道如何使用解析器
我知道有3种方法(或更多,如果我错了,请纠正我)可以被覆盖的方法
-.. etc didStartElement
-.. etc didEndElement
-.. etc foundCharacters
I was looking through some documentation about it and I have no idea on how to use the parserI know that there are 3 methods (or more, please correct me if I'm 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);
}
等。等等。
当您想将变量设置为某些标签的值等操作时,要困难一些,但通常使用类变量来完成,例如 BOOL inEmployeeTag
,您在 didStartElement
:方法中将其设置为true(YES),在<$ c $中将其设置为false c> didEndElement :方法-然后在 foundCharacters
方法中检查其值。如果是,则将var分配给string的值,否则将其分配给字符串。
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
这篇关于iOS上的NSXMLParser,如何在给定xml文件的情况下使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!