How to write XML files?

后端 未结 4 1597
时光说笑
时光说笑 2021-02-10 02:36

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 n

4条回答
  •  旧时难觅i
    2021-02-10 03:16

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

提交回复
热议问题