XML to Objective-C model classes
Older iOS and macOS code often consumes XML: RSS and Atom feeds, plist-like configuration, and SOAP or custom XML APIs. This XML to Objective-C generator turns a sample document into model classes with typed @property declarations, using the QT class prefix and nullability annotations, so you have a clear target to fill while parsing.
Example
<playlist name="Road Trip">
<track id="1" duration="215">Highway Song</track>
<track id="2" duration="187">Open Road</track>
</playlist>
@interface QTPlaylist : NSObject
@property (nonatomic, copy) NSArray<QTTrack *> *track;
@property (nonatomic, copy) NSString *name;
@end
@interface QTTrack : NSObject
@property (nonatomic, copy) NSString *value;
@property (nonatomic, assign) NSInteger identifier;
@property (nonatomic, assign) NSInteger duration;
@end
Each <track> has attributes and text, so the class has properties for id and duration plus value for the song title. The id attribute is renamed identifier because id is a type in Objective-C.
Filling the models with NSXMLParser
Foundation's NSXMLParser is event-driven: it calls your delegate as it meets each element. A typical pattern keeps the object currently being built and a buffer for text:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)name
namespaceURI:(NSString *)ns qualifiedName:(NSString *)qn attributes:(NSDictionary *)attrs {
if ([name isEqualToString:@"track"]) {
self.current = [QTTrack new];
self.current.identifier = [attrs[@"id"] integerValue];
self.current.duration = [attrs[@"duration"] integerValue];
[self.text setString:@""];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
[self.text appendString:string];
}
In didEndElement you assign self.text to value and add the track to the playlist's array. Attribute values arrive as strings, so convert them with integerValue, doubleValue or boolValue.
Where XML still shows up on Apple platforms
Even in JSON-first apps, XML appears in RSS and Atom feeds, podcast feeds, OPML subscription lists, SOAP services in enterprise apps, and appcast feeds used by the Sparkle update framework on macOS. Generating models from a real sample of such a feed gives you a checked list of every element and attribute to handle in your parser delegate, which is easy to lose track of in a long didStartElement method.
Notes
- The helper methods in full mode (
fromJSONDictionary:) read dictionaries shaped like the tool's JSON view of your XML, not XML itself. - Namespace prefixes are dropped in property names; enable
shouldProcessNamespaceson the parser if you need the namespace URIs. - Include two or more of each repeated element in the sample so it is typed as an
NSArray.
Format the classes with the Objective-C Formatter. For Swift projects, XML to Swift produces structs instead. Check the XML with the XML Formatter. Generation runs in your browser.