如何将nsstring转换为nsdictionary?

Sag*_*ari 0 cocoa objective-c

我经历了以下问题.

将NSString转换为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>";
Run Code Online (Sandbox Code Playgroud)

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

dictionary key = Category_Id      | value = 5 
dictionary key = Category_Name    | value = ???
dictionary key = Category_Picture | value = ???
Run Code Online (Sandbox Code Playgroud)

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

Chr*_*ter 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
Run Code Online (Sandbox Code Playgroud)


Aze*_*utt 5

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