Represent XML content as NSData - iPhone - iphone

I have an external XML file which I want to be represented in an NSData object
I am doing this;
NSError *error;
NSString* contents = [NSString stringWithContentsOfUrl:[NSURL URLWithString:#"http://www.apple.com/"]
encoding:NSUTF8StringEncoding
error:&error];
NSData* xmlData = [contents dataUsingEncoding:NSUTF8StringEncoding];
But for some reasons, I am getting an error (does not respond)
Please help me.

Don't have time to test this out but I think you may want to try looking into NSData's dataWithContentsOfURL: or dataWithContentsOfURL:options:error: and get it directly as data.
Also, unless you just threw http://www.apple.com/ in as a placeholder, I don't believe the source of that page is valid XML. The following feed is valid xml: https://stackoverflow.com/feeds You could try that. with what you have now first and see if it works.
Hope this helps.
Updated:
Without my knowing your project, you may get some benefit from using TouchXML - https://github.com/mrevilme/TouchXML which handles XML very well including what you are trying to do:
CXMLDocument *xmlDoc = [[CXMLDocument alloc] initWithContentsOfURL:(NSURL *)inURL encoding:(NSStringEncoding)encoding options:(NSUInteger)inOptions error:(NSError **)outError];

Related

iPhone parsing of XML data, Tags not appearing

I am facing a peculiar problem in parsing some xml data within my iPhone application. When I pass the xml data to NSXMLParser class for parsing, it ignores the part where the actual data starts appearing. It shows all the element names just before the data appears such as Soapenvolopebody etc. Later, I observed that the tags are appearing with '&lt'; and '&gt';symbols which is causing the problem.
I hope this requires a replacement strategy before parsing it to NSXMLParser. My questions is why iPhone is taking XML in that way? I am generating xml dynamically from a php file and comes as an XML when loaded into IE Browser. Hope you can help me to resolve the issue.
Update
I am still looking for a solution. I think the the idea of converting NSString to NSData and then passing it to NSXMLParser could accomplish parsing.
NSString* str= #"teststring";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];
I found this mentioned in the following post which I will be trying out. How do I convert an NSString value to NSData?
Update 1
I get the data in NSData format. Converted to NSString and applied replacement code to done away with &lt and &gt stuff. After that, I again converted the replaced NSString to NSData format. But still the xml is not correctly parsing using NSXMLParser.
please replace the unwonted character using this string function. please refer the below code.
NSString *theXML = [[[NSString alloc] initWithBytes: [webdata mutableBytes] length:[webdata length] encoding:NSUTF8StringEncoding]autorelease];
theXML = [theXML stringByReplacingOccurrencesOfString:#"<" withString:#"<"];
theXML = [theXML stringByReplacingOccurrencesOfString:#">" withString:#">"];
theXML = [theXML stringByReplacingOccurrencesOfString:#"&" withString:#"&"];
NSLog(#"%#",theXML);
Thanks

libxml2 example (with wrapper)

I am using the XML parser libxml2 with wrapper as given on the page
http://cocoawithlove.com/2008/10/using-libxml2-for-parsing-and-xpath.html
But i am not sure if I am using correctly and am getting errors (parsing,etc)
So could someone please provide me a complete example which i can refer and get an idea if I am doing something incorrectly.
thanks a lot for all your help in advance.
I'm using this methods too, to parse xml and html files.
For example to parse rss xml:
//add xml source
NSURL *url = [NSURL URLWithString:#"http://feeds.bbci.co.uk/news/rss.xml?edition=int"];
NSData *xmlData = [NSData dataWithContentsOfURL:url];
//parse the whole file with all tags
NSArray *rssFeedArray = PerformXMLXPathQuery(xmlData, #"//*");
NSLog(#"rssFeedArray: %#", rssFeedArray);
//* - query means the parser will go through all tags of the file. Then log the array to see the whole structure of xml.
Whith '/rss/channel/item' query you will only get the item tags element's, (or to get only the first item use '/rss/channel/item[1]').
in this case because of the bbc feed structure you can catch each item title at
[[[[rssFeedArray objectAtIndex:i] valueForKey:#"nodeChildArray"] objectAtIndex:0] valueForKey:#"nodeContent"]]
and description at
[[[[rssFeedArray objectAtIndex:i] valueForKey:#"nodeChildArray"] objectAtIndex:1]valueForKey:#"nodeContent"]]
and go on and on.

How can I locally save an XML file on an iPhone for when the device is offline?

My app is accessing data from a remote XML file. I have no issues receiving and parsing the data. However, I'd like to take the most current XML data and store it locally so - in the event that the user's internet service isn't available - the local data from the previous load is used.
Is there a simple way to do this? Or am I going to have to create an algorithm that will create a plist as the xml data is parsed? That seems rather tedious... I was wondering if there was an easier way to save the data as a whole.
Thanks in advance!
I don't know what format your XML data is in as you receive it, but using NSData might be helpful here, because it has very easy-to-use methods for reading/writing data from either a URL or a pathname.
For example:
NSURL *url = [NSURL URLWithString:#"http://www.fubar.com/sample.xml"];
NSData *data = [NSData dataWithContentsOfURL:url]; // Load XML data from web
// construct path within our documents directory
NSString *applicationDocumentsDir =
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *storePath = [applicationDocumentsDir stringByAppendingPathComponent:#"sample.xml"];
// write to file atomically (using temp file)
[data writeToFile:storePath atomically:TRUE];
You can also easily convert an NSData object to/from a raw buffer (pointer/length) in memory, so if your data is already downloaded you might do:
NSData *data = [NSData dataWithBytes:ptr length:len]; // Load XML data from memory
// ... continue as above, to write the NSData object to file in Documents dir

Encoding issue: Cocoa Error 261?

So I'm fetching a JSON string from a php script in my iPhone app using:
NSURL *baseURL = [NSURL URLWithString:#"test.php"];
NSError *encodeError = [[NSError alloc] init];
NSString *jsonString = [NSString stringWithContentsOfURL:baseURL encoding:NSUTF8StringEncoding error:&encodeError];
NSLog(#"Error: %#", [encodeError localizedDescription]);
NSLog(#"STRING: %#", jsonString);
The JSON string validates when I test the output. Now I'm having an encoding issue. When I fetch a single echo'd line such as:
{ "testKey":"é" }
The JSON parser works fine and I am able to create a valid JSON object. However, when I fetch my 2MB JSON string, I get presented with:
Error: Operation could not be completed. (Cocoa error 261.)
and a Null string. My PHP file is UTF8 itself and I am not using utf8_encode() because that seems to double encode the data since I'm already pulling the data as NSUTF8StringEncoding. Either way, in my single-echo test, it's the approach that allowed me to successfully log \ASDAS style UTF8 escapes when building the JSON object.
What could be causing the error in the case of the larger string?
Also, I'm not sure if it makes a difference, but I'm using the php function addslashes() on my parsed php data to account for quotes and such when building the JSON string.
I'm surprised no one has mentioned using a different encoding value instead of NSUTF8StringEncoding when calling [NSString stringWithContentsOfFile:encoding:error:].
I also got Cocoa error 261 when parsing a JSON file. I just went through the list of NSString encodings until one worked. Fortunately the first one worked for me: NSASCIIStringEncoding!
You can also use NSString stringWithContentsOfFile:usedEncoding:error: to try to find the correct encoding (as described here: How to use stringWithContentsOfURL:encoding:error:?).
Don't know if this is your problem, but I just had a similar thing (stringWithContentsOfFile, no JSON), and the problem was that the file had CRLF (windows) line-endings and Western-whatever-it's-called encoding. I used SubEthaEdit to convert to LF (Mac/Unix line-endings) and UTF-8 encoding, and now everything works fine.
Encoding issue: Cocoa Error 261? I solved this issue by trying different encoding. First I was using NSUTF8 then I switched to NSASCIIStringEncoding and it worked.
NSString* path = [[NSBundle mainBundle] pathForResource: #"fileName" ofType: #"type"];
NSData* data = [NSData dataWithContentsOfFile:path];
NSString *string = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"%#",string);
For future reference, if you need to override the encoding, and you're working with streams without embedded NULs, something like this might be good (I've just written a rough sketch outline here, check this code is and does want you want before using it):
NSHTTPURLResponse* resp=nil;
NSData* jsonAsImmutableData = [NSURLConnection sendSynchronousRequest:
[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://<whatever>"]]
returningResponse:&resp error:NULL];
NSMutableData*modifiedData = [NSMutableData dataWithData:jsonAsImmutableData];
char extraNulls[7] =
{0,0,0,0,0,0,0}; // is this defensive enough for your encoding?
[modifiedData appendBytes:extraNulls length:7];
NSString* jsonAsString = [NSString stringWithCString:[modifiedData bytes]
encoding:<whatever your encoding is>];
But I expect your best course of action is to check that your server is both using and claiming to use UTF-8 encoding or some other Apple iPhone supported encoding.
EDIT
altered code comment.
What helped me was just to change the physical file encoding to UTF-8. My editor had set it to the default, MacRoman, and didn't like letters with accents.

Loading data files in iPhone project

How does one read a data file in an iPhone project? For example, lets say I have a static file called "level.dat" that is structured as follows:
obstacles: 10
time: 100
obstacle1: 10,20
...
I would like to read the contents of the file into a NSString then do the parsing. How do I read the contents of a file into a string? Also, where in the project should the "level.dat" file reside? Should it be under "Resources" or just in the main directory?
Thanks in advance!
See this answer: How to fopen() on the iPhone? which shows how to get access to resources in your bundle. Once you have the path, just use [NSString stringWithContentsOfFile:encoding:error:].
NSString *path = [[NSBundle mainBundle] pathForResource: #"level" ofType: #"dat"]
NSError *error = nil;
NSString *data = [NSString stringWithContentsOfFile: path
encoding: NSUTF8StringEncoding
error: &error];
While this isn't what you asked for, consider turning your files into plists. You will have to reformat them into XML, but then you can load them straight into a NSDictionary with:
dict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"levels" ofType:#"plist"]];
Have you considered putting the data in an SQLite database instead of a flat file? I find that the API is very easy to use on the iPhone.
It is how I do all of my data storage on the phone now.
If you need help parsing the data string, there's a helpful article on Cocoa For Scientist