Objective-C 解析 XML 文件
我按照一个关于解析 XML 文件的快速教程进行操作,这就是我所拥有的。
- (void)loadDataFromXML {
NSString* path = @"/Users/samichaudry/Music/iTunes/iTunes Music Library.xml";
NSData* data = [NSData dataWithContentsOfFile: path];
NSXMLParser* parser = [[NSXMLParser alloc] initWithData: data];
[parser setDelegate:self];
[parser parse];
[parser release];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict{
if ([elementName isEqualToString:@"dict"]) {
NSString* name = [attributeDict valueForKey:@"name"];
NSString* artist = [attributeDict valueForKey:@"artist"];
NSLog(@"Name: %@, Artisit: %@", name, artist);
}
}
但在日志中我得到的只是大约 60 次;
2011-02-14 22:53:37.617 SearchLibrary[5218:a0f] 名称:(空), 艺术家:(空)
有人可以帮忙吗?谢谢,萨米。
I followed a quick tutorial on parsing an XML file, this what i have.
- (void)loadDataFromXML {
NSString* path = @"/Users/samichaudry/Music/iTunes/iTunes Music Library.xml";
NSData* data = [NSData dataWithContentsOfFile: path];
NSXMLParser* parser = [[NSXMLParser alloc] initWithData: data];
[parser setDelegate:self];
[parser parse];
[parser release];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict{
if ([elementName isEqualToString:@"dict"]) {
NSString* name = [attributeDict valueForKey:@"name"];
NSString* artist = [attributeDict valueForKey:@"artist"];
NSLog(@"Name: %@, Artisit: %@", name, artist);
}
}
But in the log all i get is this about 60 times;
2011-02-14 22:53:37.617
SearchLibrary[5218:a0f] Name: (null),
Artisit: (null)
Can anyone help? Thanks, Sami.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
属性字典不是您要寻找的。
如果您有 XML 标记:
那么在
parser:didStartElement:...
回调中:elementName
将是dict
attributeDict 将是一个包含 2 个键值对的字典: "foo" =>; “酒吧”和“巴兹”=> "42"
由于您正在解析 plist 格式的 xml 文件,因此
没有任何属性。因此,attributesDict
为空,[attributesDict objectForKey:@"name"]
返回nil
。解析 iTunes xml 文件的最简单方法是:
但是请记住,这最终可能会占用大量内存并完全降低应用程序的性能。
但是,嘿,库将会被加载。 :)
The attribute dict is not what you're looking for.
If you have the XML tag:
Then in the
parser:didStartElement:...
callback:elementName
will bedict
attributeDict
will be a dictionary with 2 key-value pairs: "foo" => "bar" and "baz" => "42"Since you're parsing an xml file in plist format, the
<dict>
does not have any attributes. Therefore, theattributesDict
is empty, and[attributesDict objectForKey:@"name"]
returnsnil
.The absolute simplest way to parse the iTunes xml file is:
Keep in mind, however, that this can end up eating a metric ton of memory and totally kill the performance of your app.
But hey, the library will be loaded. :)