iOS 上的 NSXMLParser,给定一个 xml 文件,我如何使用它 [英] NSXMLParser on iOS, how do I use it given a xml file

查看:26
本文介绍了iOS 上的 NSXMLParser,给定一个 xml 文件,我如何使用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何使用 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 文件(它在本地,顺便说一句,桌面上),检查每个元素并将它们存储在一个数组中以便以后显示/使用?

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 找到字符

I was looking through some documentation about it and I have no idea on how to use the parser I 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) 和 didEndElement: 方法中的 false - 然后在 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.

理查德

这篇关于iOS 上的 NSXMLParser,给定一个 xml 文件,我如何使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆