Thursday, May 28, 2009

[iPhone] XML parsing on iPhone SDK

There are 3 ways to handle XML document in iPhone SDK.

First of all, use NSXMLParser provided by iPhone SDK.
Rest of them, use library.

NSXMLParser use Event-Driven XML Parsing (async ).
I need a way to parse XML in sync.

So I checked the other ways.

There are 2 project that you can use.

'TouchXML' and 'libxml'.

'TouchXML' is works on the 'libxml'. So I skipped 'TouchXML' and I'll try with 'libxml'.

To use 'libxml' in your Xcode Project you have to add Framework.
And change build configuration.

Add 'libxml2.2.dylib' into your Project and

Add 'Header Seach Path' as '/usr/include/libxml2' like below image.

- Header Serach Path -


Now impoert header file for libxml(libxml/xmlmemory.h)

Use 'xmlParseMemory' to parse XML in memory.
Use 'xmlReadFile' to parse XML file.

Return type of these APIs are same 'xmlDocPtr'
You should call 'xmlFreeDoc' after finish your work.

I'll show you how we can see the elements in XML.

- (void)printElementName:(xmlNode *)a_node
{
xmlNode *cur_node = NULL;

for (cur_node = a_node; cur_node; cur_node = cur_node->next) {
if (cur_node->type == XML_ELEMENT_NODE) {
NSLog(@"node type: Element, name: %s\n", cur_node->name);
}
[self printElementName: cur_node->children];
}
}
- (void)applicationDidFinishLaunching:(UIApplication *)application {


NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"test.xml"];
xmlDocPtr doc = xmlReadFile([path UTF8String], "UTF-8", 0);

xmlNodePtr root = xmlDocGetRootElement(doc);
[self printElementName:root];
xmlFreeDoc(doc);
}

Now, you can parse XML with iPhone SDK :)

Thank you for visit my Blog.

2 comments:

  1. Wow. You are blogging in English! What a nice suprise! Then, are old posts deleted? .

    ReplyDelete
  2. I just started to blog in English.
    Actually I started it becasue of you. You told me we need a website in Eng. :)
    My old posts are in my Korean Blogs. I'll move them to here.

    ReplyDelete