Parse XML in iPhone (attributed not separated) - iphone

Is there a way to parse an XML in iOS where the attribute are not separated
e.g:
Users
UserId="1" Name="John Smith" Loc="London"
UserId="2" Name="Johnny Cash" Loc="Nashville"
Users
Thanks

It seams like you havent got xml at all. You are missing all usefully symbols that would normally help with the parsing. You taks is to parse a new format specification.
My first bit of advice is to ask whoever is providing you with this feed to put it into a proper format (JSON or plist are the easiest to work with).
Failing this, if the feed is not too big (otherwise you will hit performance issues), parse the feed manually character by character. You probably want to write a event based parser.
Split the feed line by line, perhaps using componentsSeparatedByString:
Then read characters into a string untill you hit an = that string is your key. Next read between the quotes "" That string is your value. FIre the key and the value off to a delegate.

JSON parsing classes will help you out...
NSString *responseString = #""; // your data contained string.
SBJSON *json = [[SBJSON new] autorelease];
NSArray *resultData = [json objectWithString:responseString error:&error];

Related

How to save data into an XML file

My application contains 8 TextFields. When I click the submit button I want to save all the values from the TextFields into an XML file (and generate a XML file if required). How can I do this?
Another XML writer which will get the job done is XSWI (shameless plug - I wrote that code).
There are many ways you could do this. One quick and dirty way of doing it is to generate a string in your code and insert the values
e.g.
NSString *myXML = [NSString stringWithFormat:#"<myxml><value1>%#</value1><value2>%#</value2></myxml>", textfield1, textfield2];
Then open a file and write myXML to it.
Not very elegant, but it depends on what exactly you want.
Do you need the XML file to be in a specific format? If not the easiest way is to save it as a plist (a type of xml file) by putting your strings into an array and then saving the array as a plist using
NSArray *array = [NSArray arrayWithObjects:label1.text, label2.text, label3.text, etc, nil];
[array writeToFile:fileName atomically:YES];
The nice thing about the plist is that you can easily load the string again by calling:
NSArray *array = [NSArray arrayWithContentsOfFile:filename];
If you need your XML in a different format from what the plist produces, the easiest way is probably just to build the XML yourself using string concatenation, e.g.
NSString *xml = [NSSString stringWithFormat:#"<root><label>%#</label><label>%#</label><label>%#</label>etc</root>", label1.text, label2.text, label3.text, etc];
You can use GDATAXML to read and write XML to file.
Refer this link to see how its done.
http://www.raywenderlich.com/725/how-to-read-and-write-xml-documents-with-gdataxml

'?' in strings breaking my XML parser

The parsing of a file containing XML breaks when ever there is a string containing '?'. As an example you can see the line below.
<Radio id="32">
<stationName>BBC 5 Live</stationName>
<streamType>aac+</streamType>
<streamBandwidth>48kbps</streamBandwidth>
<streamURL>http://bbcmedia.ic.llnwd.net/stream/bbcmedia_he2_5live_q?s=1308038932&e=1308053332&h=868e4fa343b375695183f6a3bd0267d9</streamURL>
</Radio>
Is there some way to encode the '?' or what is the way thats generally used to handle this kind of problem, as I would imagine this would be encountered a lot.
The line of code that handles this (i believe) is :
[aRadio setValue:currentElementValue forKey:elementName];
Though I maybe that is not where it breaks.
Many Thanks,
-Code
Most probably, the problem is not the '?' character, but the '&' characters in your URL. The '&' character has a special meaning in XML (it is used to start entities like & or <), so the XML parser will fail if it doesn't find a valid entity. The way to go is to wrap the value in a CDATA section as deanWombourne suggests.
Try this. Convert it into UTF8
NSData *data = [myString dataUsingEncoding:NSUTF8StringEncoding];
Then parse with this data...
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
There's a few ways of dealing with this.
1) Percent encode the string before sending from the server (your '?' would become '%3F') and decode the data when you receive in in your app. - see this answer for more details.
2) Use CDATA markers around this bit of data - see here for more details

Sending array through email on iphone

Hey guys I need to send the content of an NSMutableArray through email. I have a mailing function but I'm not sure on how to place the content of the array into a NSString to be displayed on the email under each other. Is there a way to place all the content of the array into the string with maybe HTML nextline command between each array element?
NSString *emailBody = #"Need to put the body here";
Thanks
I'll suggest you convert your array into a text string using JSON. Then place the text in the email, send it away and use JSON on the receiving end to reconstruct the array.
You can get an iPhone version of JSON called TouchJSON here.
Claus
This process is known as serialization. Apple has a guide for it, that's worth reading through.
The simplest way is to call the array's description method which will return a human readable plist in a NSString.
If you need to reconstitute the array from the email. You will need save the array as xml plist using the writeToFile: method. Then read the file back in as a string. To reconstitute you will need to extract the xml from the email, put it in a NSString, write that to file, then read it back into an NSArray.
(IIRC, there used to be a way to write to NSString as if it was a file but I can't remember how to do it anymore. Probably, writing to a NSFileHandle and reading it back instantly.)
Edit:
Can you please explain more on the
array's description method please.
Like so:
NSArray *myArray=[NSArray arrayWithObjects:#"Obj1",#"Obj2",#"Obj3",nil];
NSLog(#"myArray=%#",[myArray description]);
...prints:
myArray=(
Obj1,
Obj2,
Obj3
)
For your project you can do:
NSString *arrayString=[myArray description];
The is also a descriptionWithLocale that will print the array in different languages. I don't have a ready example for that. See NSArray, NSLocale and The Locales Programming Guide

get element value

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.
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]];
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.
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.

How do I use comma-separated-values received from a URL query in Objective-c?

How do I use comma-separated-values received from a URL query in Objective-c?
when I query the URL I get csv such as ("OMRUAH=X",20.741,"3/16/2010","1:52pm",20.7226,20.7594).
How do I capture and use this for my application?
You have two options:
Use a CSV parser: http://freshmeat.net/projects/ccsvparse
Or parse the data yourself into an array:
// myString is an NSString object containing your data
NSArray *array = [myString componentsSeparatedByString: #","];
I recently dealt with CSV parsing for Yahoo! Finance as well. I used Ragel to write a parser in C that was good enough for the CSV I was getting. It handled everything but escaped quotes, which are not going to show up much in stock quotes. It was pretty painless and a good learning experience. I'd post the code, but it was work-for-hire, so I don't own it.
Turning a C string into an NSString is easy. If you have it as an NSData, as you likely do at the end of a URL download, just do [[NSString alloc] initWithData:csvData encoding:NSUTF8StringEncoding]. If you have a pointer to a character buffer instead, use [[NSString alloc] initWithBytes:buffer length:buflen encoding:NSUTF8StringEncoding]. buflen could be strlen(buffer) if buffer is a normal, NUL-terminated C string.