Question

To start with Cocoa xml read write coding I have created a sample application, where I am able to write into XML file but getting some errors in reading. Below is the code for that.

NSXMLElement * root = [[NSXMLElement alloc ] initWithName:@"Book"]
NSXMLDocument * xmlDoc = [[NSXMLDocument alloc ] initWithRootElement: root ];
[root addChild:[NSXMLElement elementWithName: @"Name" stringValue:@"book name"]];
[root addChild:[NSXMLElement elementWithName:@"Author" stringValue:@"bool author"]];
 NSData * xmlData = [xmlDoc XMLDataWithOptions:NSXMLNodePrettyPrint];
[xmlData writeToFile:[@"~/Desktop/book.xml" stringByExpandingTildeInPath ]
 atomically:YES];
[xmlDoc release ];

This works fine and book.xml is created. But when tried to read this file, I am facing issues in opening this file. Here is the code for that.

NSString *strValue = [@"~/Desktop/book.xml" stringByExpandingTildeInPath];
NSURL * strUrl = [NSURL URLWithString:strValue];
NSError * err = nil;
NSXMLDocument  * xmlDoc = [[NSXMLDocument alloc] initWithContentsOfURL:strUrl    
options:NSXMLDocumentTidyXML error:&err];
NSXMLNode * rootNode = [xmlDoc rootElement ];
[xmlDoc release ];

value of xmlDoc is nil.

Your answers will be highly appreciated.

Thanks, Tausif.

Was it helpful?

Solution

You're missing file:// in strValue. See NSURL class documentation ... If you don't want to mess with prepending file:// manually, you should use fileURLWithPath:isDirectory:.

Why all this?

Simplified explanation for your case - every URL does consist of scheme/protocol (http, file, https, ...), delimiter (://) and path (~/Desktop/...). And it's mandatory, not optional. When you do use URLWithString: it expects that your string is complete URL, not just part of it (missing scheme/protocol in your case).

So, if you do want to use URL instead of file path, you have to take care of file:// (when URLWithString: is used) or do use fileURLWithPath:isDirectory: where you can pass just file path.

You do this, but just warning for others, if your path does contain tilde (~) you must expand it first.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top