开发者

How to convert nsstring to nsdictionary?

开发者 https://www.devze.com 2022-12-09 09:25 出处:网络
I have gone through following question. Convert NSString to NSDictionary It is something different then my question.

I have gone through following question.

Convert NSString to NSDictionary

It is something different then my question.

My question is as follows.

NSString *x=@"<Category_Id>5</Category_Id>&开发者_JAVA百科lt;Category_Name>Motos</Category_Name><Category_Picture>http://192.168.32.20/idealer/admin/Picture/icon_bike2009819541578.png</Category_Picture>";

Now I want to convert this into a dictionary, something like this,

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

I don't know how to perform this.


Not the fastest implementation, but this would do the trick (and doesn’t require any third party libraries):

@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


If it's XML then you can use an NSXMLParser. If it's not then you can write your own parser.


You could do it with a regular expression... Something like <([^>]+)>([^<]+)</\1> would grab the key into capture 1 and the value into capture 2. Iterate over the matches and build the dictionary.

This uses 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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号