【问题标题】:Cocoa/Objective-C : Best Practice to parse XML Document?Cocoa/Objective-C:解析 XML 文档的最佳实践?
【发布时间】:2011-01-15 07:36:09
【问题描述】:

我以前从未在 Cocoa 中使用过 XML,所以我不知道从哪里开始。 现在我需要将一个 XML 文件(来自硬盘)解析为一个对象,甚至是一个对象数组。

我的 XML 看起来像这样

<Person>
   <FirstName>
   <LastName>
   etc...
</Person>
<Person>
...

在我的项目中,我已经有了一个具有所需属性的 Person 类。从此类 XML 文件创建对象的最佳做法是什么?

【问题讨论】:

    标签: objective-c xml cocoa


    【解决方案1】:

    希望这会有所帮助。

    请看:

    http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/XMLParsing/Articles/UsingParser.html#//apple_ref/doc/uid/20002264-BCIIJEEH

    打开文件:

    - (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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-06
      • 1970-01-01
      • 2013-11-08
      • 1970-01-01
      • 2010-11-11
      • 2010-10-08
      • 1970-01-01
      相关资源
      最近更新 更多