Cocoa / Objective-C:解析XML文档的最佳实践? [英] Cocoa/Objective-C : Best Practice to parse XML Document?
本文介绍了Cocoa / Objective-C:解析XML文档的最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从来没有使用XML在Cocoa之前,所以我不知道从哪里开始。
现在我需要将一个XML文件(从硬盘)解析成一个对象或者甚至一个对象数组。
I never worked with XML in Cocoa before so I have no idea where to begin. Right now I need to parse a XML File (from Hard disc) into an object or even an Array of objects.
我的XML看起来像这样
My XML looks like this
<Person>
<FirstName>
<LastName>
etc...
</Person>
<Person>
...
$ b $ p在我的项目中,我已经有一个Person类具有必需的属性。从这种XML文件创建对象的最佳做法是什么?
In my project I already have a Person class with a required properties. What is the best practice to create objects from such XML file?
推荐答案
希望这有助于。
请参阅:
打开文件:
- (void)openXMLFile {
NSArray *fileTypes = [NSArray arrayWithObject:@"xml"];
NSOpenPanel *oPanel = [NSOpenPanel openPanel];
NSString *startingDir = [[NSUserDefaults standardUserDefaults] objectForKey:@"StartingDirectory"];
if (!startingDir)
startingDir = NSHomeDirectory();
[oPanel setAllowsMultipleSelection:NO];
[oPanel beginSheetForDirectory:startingDir file:nil types:fileTypes
modalForWindow:[self window] modalDelegate:self
didEndSelector:@selector(openPanelDidEnd:returnCode:contextInfo:)
contextInfo:nil];
}
- (void)openPanelDidEnd:(NSOpenPanel *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
NSString *pathToFile = nil;
if (returnCode == NSOKButton) {
pathToFile = [[[sheet filenames] objectAtIndex:0] copy];
}
if (pathToFile) {
NSString *startingDir = [pathToFile stringByDeletingLastPathComponent];
[[NSUserDefaults standardUserDefaults] setObject:startingDir forKey:@"StartingDirectory"];
[self parseXMLFile:pathToFile];
}
}
解析:
- (void)parseXMLFile:(NSString *)pathToFile {
BOOL success;
NSURL *xmlURL = [NSURL fileURLWithPath:pathToFile];
if (addressParser) // addressParser is an NSXMLParser instance variable
[addressParser release];
addressParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
[addressParser setDelegate:self];
[addressParser setShouldResolveExternalEntities:YES];
success = [addressParser parse]; // return value not used
// if not successful, delegate is informed of error
}
这篇关于Cocoa / Objective-C:解析XML文档的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文