简体   繁体   English

从XML NSData表示中获取NSDictionary的快速方法?

[英]Quick way to get an NSDictionary from an XML NSData representation?

I've loaded an XML file as NSData into memory and parse over the elements using NSXMLParser. 我已经将XML文件作为NSData加载到内存中,并使用NSXMLParser解析了元素。 Although it works, it's a very ugly and hard to maintain code since there are about 150 different elements to parse. 尽管它可以工作,但是由于要解析大约150个不同的元素,因此很难维护代码。

I know there are nice third-party solutions, but I want to keep it with the iPhone SDK for purpose of practice and fun. 我知道有不错的第三方解决方案,但我想将它与iPhone SDK保持在一起,以进行练习和娱乐。

So I thought: Why not convert that XML file into an NSDictionary? 所以我想:为什么不将该XML文件转换为NSDictionary? Having this, I could use fast enumeration to go over the elements. 有了这个,我可以使用快速枚举遍历所有元素。

Or is it just the same amount of ugly code needed to parse and process an XML right away with NSXMLParser? 还是使用NSXMLParser立即解析和处理XML所需的丑陋代码量是否相等?

Would I build up an NSDictionary for every found node in the XML and create a huge one, containing the whole structure and data? 我是否会为XML中找到的每个节点建立一个NSDictionary,并创建一个包含整个结构和数据的巨大节点? Or is there an even simpler way? 还是有一个更简单的方法?

那里有很多解析器(例如XPathQuery,TouchXML等)。

NSDictionary cannot read any random xml format. NSDictionary无法读取任何随机的xml格式。 It can only read xml in a specific format which is the plist format. 它只能以特定格式(即plist格式)读取xml。

The plist actually predates xml and the current plist format is just an xml version of the original. plist实际上早于xml,而当前的plist格式只是原始格式的xml版本。 The name plist is a contraction of "property list" as the files define the properties of an instance of a class. 名称plist是“属性列表”的缩写,因为文件定义了类实例的属性。 Therefore, all the xml tags in the file must define elements of an instance of class that implements the NSCoder protocol. 因此,文件中的所有xml标记必须定义实现NSCoder协议的类的实例的元素。

So, yes, if you start with arbitrary xml you must laboriously parse it to convert it into an NSDictionary or some other class. 因此,是的,如果您以任意xml开头,则必须费力地解析它以将其转换为NSDictionary或其他类。

I wouldn't bother writing a parser from scratch for any reason except as a learning exercise. 除了作为学习练习之外,我不会因为任何原因从头开始编写解析器。 Every single xml format requires a different parser. 每种xml格式都需要不同的解析器。 It's better to use an existing parser so that 80% of the work is done for you. 最好使用现有的解析器,以便为您完成80%的工作。 In a real project, you will end up doing that anyway. 在真实的项目中,您最终还是要这样做。

Hi dontWatchMyProfile, You should better user NSString XML format. 嗨,dontWatchMyProfile,您最好使用NSString XML格式。 For this format, I have a little lib converting easily 对于这种格式,我有一点lib可以轻松转换

http://bcaccinolo.wordpress.com/2010/11/14/xml-to-nsdictionary-converter/ http://bcaccinolo.wordpress.com/2010/11/14/xml-to-nsdictionary-converter/

I hope it might help. 希望对您有所帮助。

Cheers, Benoit 干杯,贝努瓦

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM