当我从 Internet 获取 XML 文件然后对其进行解析时,我遇到了这个问题,我得到了这个错误:
Error while parsing the document: Error Domain=SMXMLDocumentErrorDomain Code=1 "Malformed XML document. Error at line 1:1." UserInfo=0x886e880 {LineNumber=1, ColumnNumber=1, NSLocalizedDescription=Malformed XML document. Error at line 1:1., NSUnderlyingError=0x886e7c0 "The operation couldn’t be completed. (NSXMLParserErrorDomain error 5.)"}
这是代码的摘录(我相信我只显示最相关的代码,如果您需要更多,请询问。)
// Create a URL Request and set the URL
NSURL *url = [NSURL URLWithString:@"http://***.xml"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// Display the network activity indicator
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
// Perform the request on a new thread so we don't block the UI
dispatch_queue_t downloadQueue = dispatch_queue_create("Download queue", NULL);
dispatch_async(downloadQueue, ^{
NSError* err = nil;
NSHTTPURLResponse* rsp = nil;
// Perform the request synchronously on this thread
NSData *rspData = [NSURLConnection sendSynchronousRequest:request returningResponse:&rsp error:&err];
// Once a response is received, handle it on the main thread in case we do any UI updates
dispatch_async(dispatch_get_main_queue(), ^{
// Hide the network activity indicator
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
if (rspData == nil || (err != nil && [err code] != noErr)) {
// If there was a no data received, or an error...
NSLog(@"No data received.");
} else {
// Cache the file in the cache directory
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString* path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"init.xml"];
//NSLog(@"%@",path);
[[NSFileManager defaultManager] removeItemAtPath:path error:nil];
[data writeToFile:path atomically:YES];
//NSString *sampleXML = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"xml"];
NSData *data = [NSData dataWithContentsOfFile:path];
// create a new SMXMLDocument with the contents of sample.xml
NSError *error;
SMXMLDocument *document = [SMXMLDocument documentWithData:data error:&error];
// check for errors
if (error) {
NSLog(@"Error while parsing the document: %@", error);
// return;
}
首先,我已将 iPhone 连接到一个 XML 提要,它已获取并写入变量路径的路径。然后我检查 XML 文档中的错误,每次都会收到该错误。
但是,如果我使用放置在应用程序主文件夹中的本地 XML 文件,则获取所有数据没有问题。
使用代码:
NSString *sampleXML = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"xml"];
那么有人知道我做错了什么吗?似乎它没有下载 XML 文件并将其存储到 iPhone 的缓存中,但是 NSLog(); 似乎以不同的方式显示它。显然本地文件与互联网上的文件相同。
此外,我已经尝试将文件保存到路径中,但没有任何结果。