Come scrivere i file XML?
-
27-09-2019 - |
Domanda
Voglio scrivere un file di grandi dimensioni non è così complicato, ma nel mio app e in grado di inviare per posta (tramite MFMailComposeViewController) Dal momento che NSXMLElement e classi correlate non sono portato su iPhone SDK che opzioni ho per la creazione di documenti XML? Grazie in anticipo.
Soluzione
Shameless auto-promozione: KSXMLWriter
Altri suggerimenti
Prova open source XML flusso scrittore per iOS :
- Scritto in Objective-C, un singolo .h. e il file .m
- Una @protocol per il supporto dello spazio dei nomi e uno per senza
Esempio:
// 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];
Questo produce la seguente stringa XML:
<Root>Text content for root element</Root>
E 'un esercizio di compiti a casa in costruzione NSString. Astrattamente, creare un protocollo come:
@protocol XmlExport
-(NSString*)xmlElementName;
-(NSString*)xmlElementData;
-(NSDictionary*)xmlAttributes;
-(NSString*)toXML;
-(NSArray*)xmlSubElements;
@end
Assicurarsi che tutto si sta salvando l'implementa e costruire il codice XML con qualcosa di simile al seguente:
-(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;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow