The XML file parsed is the following:
It is parsed using at application startup using the following code:<?xml version="1.0" encoding="UTF-8"?>
<root>
<person>
<name>John Doe</name>
<age>14</age>
</person>
<person>
<name>Mary Doe</name>
<age>14</age>
</person>
<person>
<name>John Smith</name>
<age>15</age>
</person>
</root>
To parse it using MAX you need to add MPWXmlKit and MPWFoundation to your project, and then replace the code above with the following:- (void)applicationDidFinishLaunching:(NSNotification*)notification
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"xmlExample" ofType:@"xml"];
NSData *xmlData = [NSData dataWithContentsOfFile:path];
xmlTextReaderPtr reader = xmlReaderForMemory([xmlData bytes],
[xmlData length],
[path UTF8String], nil,
(XML_PARSE_NOBLANKS | XML_PARSE_NOCDATA | XML_PARSE_NOERROR | XML_PARSE_NOWARNING));
if (!reader) {
NSLog(@"Failed to load xmlreader");
return;
}
NSString *currentTagName = nil;
NSDictionary *currentPerson = nil;
NSString *currentTagValue = nil;
NSMutableArray *people = [NSMutableArray array];
char* temp;
while (true) {
if (!xmlTextReaderRead(reader)) break;
switch (xmlTextReaderNodeType(reader)) {
case XML_READER_TYPE_ELEMENT:
//We are starting an element
temp = (char*)xmlTextReaderConstName(reader);
currentTagName = [NSString stringWithCString:temp
encoding:NSUTF8StringEncoding];
if ([currentTagName isEqualToString:@"person"]) {
currentPerson = [NSMutableDictionary dictionary];
[people addObject:currentPerson];
}
continue;
case XML_READER_TYPE_TEXT:
//The current tag has a text value, stick it into the current person
temp = (char*)xmlTextReaderConstValue(reader);
currentTagValue = [NSString stringWithCString:temp
encoding:NSUTF8StringEncoding];
if (!currentPerson) return;
[currentPerson setValue:currentTagValue forKey:currentTagName];
currentTagValue = nil;
currentTagName = nil;
default: continue;
}
}
NSLog(@"%@:%s Final data: %@", [self class], _cmd, people);
[self setRecords:people];
}
- (void)applicationDidFinishLaunching:(NSNotification*)notification
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"xmlExample" ofType:@"xml"];
NSArray *people=[[MPWMAXParser parser] parsedDataFromURL:[NSURL fileURLWithPath:path]];
[self setRecords:people];
}
No comments:
Post a Comment