views:

85

answers:

4

Hi.

I want to write a not so complicated but large file within my app and be able to send it by mail (using MFMailComposeViewController) Since NSXMLElement and related classes are not ported to iPhone SDK what options do I have for creating XML documents? Thanks in advance.

+1  A: 

It's a homework exercise in NSString building. Abstractly, create a protocol like:

@protocol XmlExport
-(NSString*)xmlElementName;
-(NSString*)xmlElementData;
-(NSDictionary*)xmlAttributes;
-(NSString*)toXML;
-(NSArray*)xmlSubElements;
@end

Make sure everything you're saving implements it and build the XML with something like the following:

-(NSString*)toXML {
    NSMutableString *xmlString;
    NSString *returnString;

    /* Opening tag */
    xmlString = [[NSMutableString alloc] initWithFormat:@"<%@", [self xmlElementName]];
    for (NSString *type in [self xmlAttributes]) {
        [xmlString appendFormat:@" %@=\"%@\"", type, [[self xmlAttributes] valueForKey:type]];
    }   
    [xmlString appendString:@">"];

    /* Add subelements */
    for (id<XmlExport> *s in [self xmlSubElements]) {
        [xmlString appendString:[s toXML]];
    }

    /* Data */
    if ([self xmlElementData]) {
        [xmlString appendString:[self xmlElementData]];
    }

    /* Close it up */
    [xmlString appendFormat:@"</%@>", [self xmlElementName]];

    /* Return immutable, free temp memory */
    returnString = [NSString stringWithString:xmlString];
    [xmlString release]; xmlString = nil;

    return returnString;
}
John Franklin
The release/nil line is a habit of mine that keeps me from ever having dangling pointer issues. Yes, it's unnecessary here, but the performance cost is very low and the optimizer will likely remove it. Nonetheless, it is still a habit I recommend.
John Franklin
Regarding nil'ing out your vars, see http://iphonedevelopment.blogspot.com/2010/09/dealloc.html
TomH
+1  A: 

KSXMLWriter

Mike Abdullah
A: 

Try this

http://code.google.com/p/xswi/

for a simple XML writer.

Thomas
I am somehow not able to comment John Franklins answer, but his reply is a classic FAIL as it does no XML escaping. Always use a proper serializer in production code, do not attempt the above.
Thomas
A: 

I would recommend using KissXML. The author started in a similar situation as you and created an NSXML compatible API wrapper around libxml. He discusses the options and decisions here on his blog.

codelark