0

我在 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>

有什么建议吗?

4

1 回答 1

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>"];
于 2013-03-14T20:26:33.360 回答