Pages

Sunday, August 15, 2010

XML parsing on Mac. Fast and Dirty.

If you know C better than Objective-C, this is a fast and dirty way to parse an XML-file on Mac OS X:
#import <Foundation/Foundation.h>

void PrintTree(CFXMLTreeRef tree)
{
int kids = CFTreeGetChildCount(tree);
if (kids > 0)
{
int cnt = 0;
while (cnt < kids)
{
CFXMLTreeRef treeChild = CFTreeGetChildAtIndex(tree, cnt);

PrintTree(treeChild);

CFXMLNodeRef treeNode = CFXMLTreeGetNode(treeChild);
//CFXMLNodeTypeCode subNodeType = CFXMLNodeGetTypeCode(treeNode);
CFStringRef text = CFXMLNodeGetString(treeNode);
NSLog(@"text: %@", text);
++cnt;
}
}
}

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

CFXMLTreeRef tree;
NSString *str;
NSData* data;

str = [[NSMutableString alloc] initWithContentsOfFile: @"data.xml"];
data = [str dataUsingEncoding:NSUTF8StringEncoding];

tree = CFXMLTreeCreateFromData(kCFAllocatorDefault,
(CFDataRef)data, NULL,
kCFXMLParserSkipWhitespace,
kCFXMLNodeCurrentVersion);

PrintTree(tree);

CFRelease(tree);
[str release];
[pool drain];
return 0;
}
As you see, this a Foundation Tool project. It works with data.xml located in the debug folder:
<?xml version="1.0" encoding="UTF-8"?>
<root>
  <person>
    <name>Pavel Gnatyuk</name>
    <age>40</age>
  </person>
</root>
Of course, it could be written in the pure C. But it's enough to give a direction.
BTW, the standard way to work with the XML on iPhone is shown in this nice tutorial:
Parsing XML Files

No comments:

Post a Comment