How to write XML files?

亡梦爱人 提交于 2019-12-03 09:06:16

Shameless self-promotion: KSXMLWriter

codelark

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!