Question

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.

Was it helpful?

Solution

Shameless self-promotion: KSXMLWriter

OTHER TIPS

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.

Try the open source XML stream writer for iOS:

  • Written in Objective-C, a single .h. and .m file
  • One @protocol for namespace support and one for without

Example:

// allocate serializer
XMLWriter* xmlWriter = [[XMLWriter alloc]init];

// start writing XML elements
[xmlWriter writeStartElement:@"Root"];
[xmlWriter writeCharacters:@"Text content for root element"];
[xmlWriter writeEndElement];

// get the resulting XML string
NSString* xml = [xmlWriter toString];

This produces the following XML string:

<Root>Text content for root element</Root>

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top