Raheel Sadiq
Raheel Sadiq

Reputation: 9867

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

Upvotes: 1

Views: 215

Answers (3)

ilmiacs
ilmiacs

Reputation: 2576

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.

Upvotes: 1

Just Variable
Just Variable

Reputation: 877

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

Upvotes: 2

Nicos Karalis
Nicos Karalis

Reputation: 3773

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"]

Upvotes: 1

Related Questions