Kirtikumar A.
Kirtikumar A.

Reputation: 4204

Covert XML string output to XML file

I am using XMWriter class for generating XML,but after generating my XML string I am not sure how to save it as an XML file.

.m code

[xmlWriter writeEndElement];
[xmlWriter writeStartElement:@"Miniparent"];
[xmlWriter writeStartElement:@"Child"];
[xmlWriter writeCharacters:@"Text content for root element"];
[xmlWriter writeEndElement];
[xmlWriter writeStartElement:@"Child"];
[xmlWriter writeCharacters:@"Text content for root element"];
[xmlWriter writeEndElement];

Console output

<Miniparent>
<Child>Text content for root element</Child>
<Child>Text content for root element</Child>
<Child>Text content for root element</Child>
</Miniparent>

Upvotes: 0

Views: 132

Answers (2)

Mihir Mehta
Mihir Mehta

Reputation: 13833

Convert it to an NSString object

NSString* xml = [xmlWriter toString];

then save it to file

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory

NSError *error = nil;
BOOL succeed = [xml writeToFile:[documentsDirectory stringByAppendingPathComponent:@"myXmlFile.xml"]
      atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!succeed){
    // Handle error here
}

Upvotes: 1

Kirtikumar A.
Kirtikumar A.

Reputation: 4204

I solved my question as below ,and putting this code for other users

NSFileManager *fileManager = [NSFileManager defaultManager];

//getting the path to document directory for the file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [paths objectAtIndex:0];
NSString *path = [documentDir stringByAppendingPathComponent:@"test.xml"];

//checking to see of the file already exist
if(![fileManager fileExistsAtPath:path])
{
    [fileManager createFileAtPath:path contents:[xml dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
}

Upvotes: 1

Related Questions