如何将nsstring转换为nsdictionary?

时间:2009-10-27 19:27:10

标签: objective-c cocoa

我经历了以下问题。

Convert NSString to NSDictionary

这与我的问题不同。

我的问题如下。

NSString *x=@"<Category_Id>5</Category_Id><Category_Name>Motos</Category_Name><Category_Picture>http://192.168.32.20/idealer/admin/Picture/icon_bike2009819541578.png</Category_Picture>";

现在我想把它转换成字典,就像这样,

dictionary key = Category_Id      | value = 5 
dictionary key = Category_Name    | value = ???
dictionary key = Category_Picture | value = ???

我不知道如何执行此操作。

3 个答案:

答案 0 :(得分:7)

不是最快的实现,但这可以解决问题(并且不需要任何第三方库):

@interface NSDictionary (DictionaryFromXML)

+ (NSDictionary *)dictionaryFromXML:(NSString *)xml;

@end

@implementation NSDictionary (DictionaryFromXML)

+ (NSDictionary *)dictionaryFromXML:(NSString *)xml
{
  // We need to wrap the input in a root element
  NSString *x = [NSString stringWithFormat:@"<x>%@</x>", xml];

  NSXMLDocument *doc = [[[NSXMLDocument alloc] initWithXMLString:x
                                                         options:0
                                                           error:NULL]
                         autorelease];

  if (!doc)
    return nil;

  NSMutableDictionary *dict = [NSMutableDictionary dictionary];

  for (NSXMLElement *el in [[doc rootElement] children])
    [dict setObject:[el stringValue] forKey:[el name]];

  return dict;
}

@end

答案 1 :(得分:5)

如果是XML,则可以使用NSXMLParser。如果不是那么你可以编写自己的解析器。

答案 2 :(得分:4)

你可以用正则表达式来做...像<([^>]+)>([^<]+)</\1>这样的东西会把关键抓到捕获1,把值抓到捕获2.迭代匹配并构建字典。

这使用RegexKitLite

NSString  * x = @"<Category_Id>5</Category_Id><Category_Name>Motos</Category_Name><Category_Picture>http://192.168.32.20/idealer/admin/Picture/icon_bike2009819541578.png</Category_Picture>";
NSString * regex = @"<([^>]+)>([^<]+)</\\1>";
NSArray * cap = [x arrayOfCaptureComponentsMatchedByRegex:regex];
NSMutableDictionary * d = [NSMutableDictionary dictionary];
for (NSArray * captures in cap) {
    if ([captures count] < 3) { continue; }
    NSString * key = [captures objectAtIndex:1];
    NSString * value = [captures objectAtIndex:2];
    [d setObject:value forKey:key];
}
NSLog(@"%@", d);