Amir Foghel
Amir Foghel

Reputation: 975

How can I write this XML example to an XML file?

How do I write this so it will be saved in an XML file?

<Stations>
    <station id="1">
        <title>Lehavim Railway station</title>
        <latitude>31.369834</latitude>
        <longitude>34.798207</longitude>
    </station>
</Stations>

I have this part of code, but I don't know how to arrange it so that it will be saved as shown above.

    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                                                          NSUserDomainMask, 
                                                          YES);

    NSString * filePath = [paths objectAtIndex:0];

    filePath = [filePath stringByAppendingPathComponent:@"favorite"];
    filePath = [filePath stringByAppendingPathExtension:@"xml"];

    NSDictionary *station = [NSDictionary dictionaryWithObjectsAndKeys:
                              @"Lehavim Railway station",
                              @"31.369834",
                              @"34.798207",
                              , nil  ];

    [station writeToFile:filePath atomically:YES];

I also don't know how to change the id in the station part.

Upvotes: 1

Views: 621

Answers (1)

Michael Dautermann
Michael Dautermann

Reputation: 89509

On the local iOS file system, XML files look the same as the plist files written out by NSDictionary or NSArray so programmers can frequently "cheat" (or take a short cut?) by writing out nested dictionaries or arrays and considering them XML files.

Except these files are not XML. And you can't write out XML-style attributes (i.e. the id = "1" bit in your example up there) via the standard NSDictionary or NSArray writeToFile: methods.

You need to decide on a class that creates XML objects and allows you to write them out.

Here is a related question with a selection of answers & choices that can help you figure out the right way to go. For my own projects, I really like libxml2.

Upvotes: 1

Related Questions