How to write XML files?

后端 未结 4 1588
时光说笑
时光说笑 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条回答
  • 2021-02-10 03:04

    Shameless self-promotion: KSXMLWriter

    0 讨论(0)
  • 2021-02-10 03:07

    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.

    0 讨论(0)
  • 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<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;
    }
    
    0 讨论(0)
  • 2021-02-10 03:23

    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>
    
    0 讨论(0)
提交回复
热议问题