2011-08-18 4 views
9

Ottengo i dati da un file XML e lo sto memorizzando nell'oggetto NSData. Voglio convertire quel NSData in un NSDictionary e memorizzarlo in un plist.Conversione di NSData in NSDictionary

Il mio codice è il seguente:

NSURL *url = [NSURL URLWithString:@"http://www.fubar.com/sample.xml"]; 
    NSData *data = [NSData dataWithContentsOfURL:url]; 
    NSLog(@"%@", data); 

per convertire i dati, sto usando:

- (NSDictionary *)downloadPlist:(NSString *)url { 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10]; 
    NSURLResponse *resp = nil; 
    NSError *err = nil; 
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&resp error:&err]; 

    if (!err) { 
     NSString *errorDescription = nil; 
     NSPropertyListFormat format; 
     NSDictionary *samplePlist = [NSPropertyListSerialization propertyListFromData:responseData mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&errorDescription]; 

     if (!errorDescription) 
      return samplePlist; 

     [errorDescription release];    
    } 

    return nil; 
} 

Qualcuno può dirmi come fare?

+0

Beh, è ​​necessario leggere il file XML ed estrarre gli elementi XML che appartengono nel dizionario. Il modo in cui lo fai dipende dalla struttura del file XML. –

risposta

2

provare questo codice:

NSString *newStr1 = [[NSString alloc] initWithData:theData1 encoding:NSUTF8StringEncoding]; 
NSString *newStr2 = [[NSString alloc] initWithData:theData2 encoding:NSUTF8StringEncoding]; 
NSString *newStr3 = [[NSString alloc] initWithData:theData3 encoding:NSUTF8StringEncoding]; 

NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", @"key3", nil]; 
NSArray *objects = [NSArray arrayWithObjects:newStr1 , newStr2 , newStr3 , nil]; 
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys]; 

for (id key in dictionary) { 
    NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]); 
} 

NSString *path = [[NSBundle mainBundle] pathForResource:@"Login" ofType:@"plist"]; 
[dictionary writeToFile:path atomically:YES]; 
//here Login is the plist name. 

Felice di codifica

5

o questo:

NSString* dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
SBJSON *jsonParser = [SBJSON new]; 
NSDictionary* result = (NSDictionary*)[jsonParser objectWithString:dataStr error:nil]; 
[jsonParser release]; 
[dataStr release]; 
+0

Grazie per questo :) – Muzammil

+0

Questo funziona solo per i dati JSON e la domanda riguarda i dati XML. – Brian

+0

Che cos'è SBJSON? –