nacho4d
nacho4d

Reputation: 45078

How to write XML files?

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.

Upvotes: 5

Views: 7235

Answers (4)

codelark
codelark

Reputation: 12334

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.

Upvotes: 3

Mike Abdullah
Mike Abdullah

Reputation: 15003

Shameless self-promotion: KSXMLWriter

Upvotes: 2

ThomasRS
ThomasRS

Reputation: 8287

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>

Upvotes: 2

John Franklin
John Franklin

Reputation: 4912

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;
}

Upvotes: -1

Related Questions