tags:

views:

47

answers:

3

Hello guys.

I have a NSString like that? (in iPhone application)

  NSString *xmlStr =  "<?xml version=1.0 encoding=UTF-8>
                         <information>
                             <name>John</name>
                             <id>435346534</id>
                             <phone>045635456</phone>
                             <address>New York</address>
                         </information>" 

How I can get elements value? (Do i need convert to XML format and get elements value? or split string? any way please tell me?)

Thank you guys.

A: 

Your string is in xml format already and you need to parse it to retrieve data. There're several options available - for example you can use NSXMLParser class or libxml library.

Edit: XMLPerformance sample project shows how to use both approaches and compare their performance.

Vladimir
Do you have source code?
haicnpmk44
A: 

The most obvious solution is to use an XML parser to retrieve the values from each element.

You could use the excellent TBXML for this task. It provides a really simple interface where it wouldn't take more than a few lines to retrieve the desired values. The drawback to using this small library is that it (as far as I know) loads the entire XML data into memory. In this particular case, however, that is not problem at all.

There's of course also the option of using the NSXMLParser, though this is an event-driven parser, and thus a bit less simple to use.

Jacob H. Hansen
A: 

If you want to use split string, you can use tokenization of strings using "componentsSeparatedByString" method. This is a more cumbersome method of course, rather than the recommended XMLParser

To get the name.

NSArray *xmlStr_first_array = [xmlStr componentsSeparatedByString: @"<name>"];

NSString *xmlStr_split = [NSString stringWithFormat:@"%@",[xmlStr_first_array objectAtIndex:1]];

NSArray *xmlStr_second_array = [xmlStr_split componentsSeparatedByString: @"</name>"];

NSString *name = [NSString stringWithFormat:@"%@",[xmlStr_second_array objectAtIndex:0]];
erastusnjuki
I somewhat disagree with this approach...
Vladimir
@Vladimir. It is certainly not recommended. Help this guy by listing the disadvantages. You certainly have more than I do.
erastusnjuki
Hard to say... its just wrong way to handle xml :)
Vladimir