简体   繁体   中英

NSdictionary element from xml

i have a situation I am getting data from the server as xml, i converted that data into NSDictionary using https://github.com/Insert-Witty-Name

MY xml is like

<Game>
      <userid></userid>
      <name></name>
      <friendId></friendId>
      <friendName></friendName>
</Game>

the value Game and all other items can change, so first I need to find out the name of the first element that is a game =>

I converted this through above Library now I am getting as

 xmlString = [NSString stringWithFormat:@"<Game><userid>12</userid><userName>ben</userName><friendId>41</friendId><friendName>Ben1</friendName></Game>"];

NSDictionary *dict = [XMLReader dictionaryForXMLString:xmlString error:nil];

NSString *string;
string = [dict objectForKey:@"Game"];
NSLog(@"name is :%@",string);

and the output is

{
friendId = 41;
friendName = Ben1;
userName = ben;
userid = 12;
}

I need to find out the root element name of xml and how to access these values in NSDictionary with objectForKey

string = [[dict objectForKey:@"Game"] objectForKey:@"userName"]; 

use Enumerator to iterate and find value based on the key or
[[dict objectForKey:@"Game"] allKeys] to get all keys

So you want the result to be "ben" , correct? Well, [dict objectForKey:@"Game"]; is not an NSString but an NSDictionary . You get no error because there is no way for LLVM to check this at compile time, so it happily will build. The conversion to a string happens in the parsing into the format string "%@" . Instead, what you want is this:

string = [[dict objectForKey:@"Game"] objectForKey:@"name"];

EDIT: Different question as becomes clear from the comments...

Or do you rather need "Game" ? In which case

NSString* rootName = [[dict allKeys] firstObject];

Will give you always the correct answer, since there always is only one root.

If your xml can change

this:

<Game>
      <userid></userid>
      <name></name>
      <friendId></friendId>
      <friendName></friendName>
</Game>

becoming this:

<Status>
      <userid></userid>
      <name></name>
      <friendId></friendId>
      <friendName></friendName>
</Status>

then you have to dynamically find the dictionary keys, using the method allKeys

like this:

[dict allKeys]

on my first example the result will be: ["Game"] and on the second: ["Status"]

if you need the keys of the inner element just do like this:

[[dict objectForKey:@"Game"] allKeys]

this will return: ["userid","name","friendId", "friendName"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM