2013-03-13 63 views
0

我在xcode中工作;我有一個NSArray的數據,我想轉換成XML文件,然後上傳到Web數據庫。我如何將NSArray放入XML文件並上傳到URL

該陣列格式如下:

555ttt Conor Brady testpass BC test Desc this is user timestamp this is location this is user location

我希望它轉換成XML文件,如下圖所示:

<plates> 
<plate> 
<plateno>555ttt</plateno> 
<user>Conor Brady</user> 
<username>cbrady</username> 
<password>testpass</password> 
<province>BC</province> 
<description>test desc</description> 
<usertimestamp>this is user timestamp</usertimestamp> 
<location>this is user location</location> 
<status>this is user status</status> 
</plate> 
<plate> 
<plateno>333yyy</plateno> 
<user>C Brady</user> 
<username>cbrady</username> 
<password>testpass</password> 
<province>BC</province> 
<description>This is a test description</description> 
<usertimestamp>this is user timestamp</usertimestamp> 
<location>this is user location</location> 
<status>this is user status</status> 
</plate> 
</plates> 

什麼建議嗎?

回答

0

您需要創建一個從數組中的數據到要生成的XML中的標籤的映射。最簡單的方法是爲每個要添加到XML的平板創建一個字典。像這樣的事情應該做的伎倆:

// Encode the data in an array of dictionaries 
// Each dictionary has a key indentifying the XML tag 
NSDictionary *plate1 = @{@"plateno" : @"555ttt", @"user" : @"Conor Brady", @"password" : @"testpass", @"province" : @"BC", @"description" : @"test desc", @"location" : @"this is user location"}; 
NSDictionary *plate2 = @{@"plateno" : @"333yyy", @"user" : @"C Brady", @"password" : @"testpass", @"province" : @"BC", @"description" : @"test desc", @"location" : @"this is user location"}; 
NSArray *platesData = @[plate1, plate2]; 

// Build the XML string 
NSMutableString *xmlString = [NSMutableString string]; 

// Start the plates data 
[xmlString appendString:@"<plates>"]; 

for (NSDictionary *plateDict in platesData) { 
    // Start a plate entry 
    [xmlString appendString:@"<plate>"]; 

    // Add all the keys (XML tags) and values to the string 
    [plateDict enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop){ 
     [xmlString appendFormat:@"<%@>%@</%@>", key, value, key]; 
    }]; 

    // End a plate entry 
    [xmlString appendString:@"</plate>"]; 
} 

// End the plates data 
[xmlString appendString:@"</plates>"];