如何将NSArray放入XML文件并上传到URL

时间:2013-03-13 00:22:03

标签: xml xcode nsarray

我在xcode工作;我有一个NSArray数据,我想将其转换为XML文件,然后上传到Web数据库。

数组的格式如下:

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>

有什么建议吗?

1 个答案:

答案 0 :(得分: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>"];