2011-08-18 207 views
9

我從XML文件中獲取數據,並將其存儲在NSData對象中。我想將該NSData轉換爲NSDictionary並將數據存儲在plist中。將NSData轉換爲NSDictionary

我的代碼如下:

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

將數據轉換,我使用:

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

誰能告訴我該怎麼做?

+0

那麼,你需要讀取XML文件,解壓縮,在你的字典所屬的XML元素。你怎麼做取決於XML文件的結構。 –

回答

2

試試這個代碼:

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. 

快樂編碼

5

或本:

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

感謝:) – Muzammil

+0

這隻適用於JSON數據,問題是關於XML數據。 – Brian

+0

什麼是SBJSON? –