I'm trying to download an online file, save it locally and then, parse it with TBXML!
The problem is that TBXML works only with this code:
TBXML *tbxml = [[TBXML tbxmlWithXMLFile:@"data.xml"] retain];
For the download i'm using this code:
NSError *err = [[[NSError alloc] init] autorelease];
NSString *url = [[NSString stringWithF开发者_开发技巧ormat:@"http://url/data.xml"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *myFile = [NSString stringWithContentsOfURL:[NSURL URLWithString:url] encoding:NSUTF8StringEncoding error:&err];
and it works! Now i have all the data into "myFile" NSString!
For write it into a file, i'm using this (and probably here there is the problem!)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSError *error;
NSString *myFile = [documentsDirectory stringByAppendingPathComponent:@"abc.xml"];
BOOL succeed = [myTxtFile writeToFile:myFile atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!succeed){
NSLog(@"no");
}
and it works! if i do this
NSString *myString = [[NSString alloc] initWithContentsOfFile:myFile encoding:NSUTF8StringEncoding error:NULL];
NSLog(@"%@", myString);
it works, i see all the data from the xml!
The problem is when i call the method to parse it with TBXML
this
TBXML *tbxml = [[TBXML tbxmlWithXMLFile:myString] retain];
crash! I think that TBXML need a local file, saved into the project directory!
How can i do this? thank you! :)
There are also other initializers, for example, you might want to try this one:
TBXML *tbxml = [[TBXML alloc] initWithXMLString:myString];
where myString
contains the raw XML string. Or better yet:
TBXML *tbxml = [[TBXML alloc] initWithURL:[NSURL URLWithString:@"http://url/data.xml"];
which completely eliminates your need of dealing with files and paths.
See the API documentation for details.
From the code you posted, myString contains the whole XML. You should be doing
TBXML *tbxml = [[TBXML tbxmlWithXMLFile:@"abc.xml"] retain];
You have to pass myFile
, not myString
as argument to tbxmlWithXMLFile:
. But if it crashes due to a non-existing file you better reevaluate whether you really want to use that library.
精彩评论