Wednesday, April 20, 2011

Load an XML file in Mac Os X using Cocoa: NSXMLDocument

Here another snippet on how to load an XML file using the NSXMLDocument class. Our goal is to show an “Open File” dialog box (as said in the last post), chose an xml file, and put it in a data structure (NSXMLDocument)

Here’s the code:

-(BOOL) LoadXml : (NSError **)err
{
    NSURL *fileUrl = nil;
    
    NSOpenPanel* openDlg = [NSOpenPanel openPanel];
    [openDlg setCanChooseFiles:YES];
    [openDlg setCanChooseDirectories:NO];
    [openDlg setAllowsMultipleSelection: NO];
    [openDlg setAllowedFileTypes:[NSArray arrayWithObjects:@"xml", 
             nil]];
    if ( [openDlg runModal] == NSOKButton )
    {
        fileUrl = [openDlg URL];
    }
    if (fileUrl==nil)
    {
        return NO;
    }
    
    xmlDoc = [[NSXMLDocument alloc] initWithContentsOfURL:fileUrl 
       options:(NSXMLNodePreserveWhitespace|NSXMLNodePreserveCDATA)
       error:err];
    if (xmlDoc == nil) {
        xmlDoc = [[NSXMLDocument alloc] initWithContentsOfURL:fileUrl
           options:NSXMLDocumentTidyXML error:&err];
    }
    if (xmlDoc == nil) 
  return NO;
    
    ...
}

The only “strange” thing suggested by the Apple’s example and reported here, is the double initialization of NSXMLDocument, with different parameters: the first one with NSXMLNodePreserveWhitespace|NSXMLNodePreserveCDATA, the second one with NSXMLDocumentTidyXML.

We are trying to recover from parsing errors. NSXMLDocumentTidyXML reformats the document before the parsing. Hopefully it can correct some error, but it modifies the original file (take a look at the documentation).

More information is in the “Introduction to Tree-Based XML Programming Guide for Cocoa” on the Apple Devveloper web site.

No comments:

Post a Comment