tiistai 6. marraskuuta 2012

How to parse a plist that has multiple dictionary items

I was surfing Stack Overflow and everywhere to find out how I would parse a bit more complicated plist XML than the usual examples around the Internet sites. In this case it is a munki catalog file that needs to be parsed. On main level the first item is array and under that next item is dict. Under that is the actual thing where the key value pairs of interest are located. So finally ended up with this (each dict on main level array has to be enumerated first using enumerator and then cast the resulting object to a new dictionary and then parse that), what makes this tricky is that many examples are not working, but they are just crashing. This should work:
    // replace /mypath with your path to your file
    NSString *dataPath = @"/mypath/mycomplexplist.plist";
    NSString *errorDesc = nil;
    NSPropertyListFormat format;
    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]) {
        // Handle the error if the file does not exist
     
    }
    NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:dataPath];
    NSDictionary *dictionary = (NSDictionary *)[NSPropertyListSerialization
                                          propertyListFromData:plistXML
                                          mutabilityOption:NSPropertyListMutableContainersAndLeaves
                                          format:&format
                                          errorDescription:&errorDesc];
    if (!dictionary) {
        // Handle your error
    }
       
    NSEnumerator *enumerator = [dictionary objectEnumerator];
    
    for(id object in enumerator) {
        NSDictionary *innerdic = object;
        NSString *name = [innerdic objectForKey:@"name"];
        NSLog(@"name =%@",name);
        // and parse the rest of the stuff of the interest here.
    }        

Ei kommentteja:

Lähetä kommentti