Thursday 13 September 2007

import xml into NSDictionary

I've spent the last few days fiddling on an NSXMLNode category that creates a method called

xmlToDictionary

+(NSDictionary) xmlToDictionary:node


You just give it an xml node and it returns a dictionary that you can query like this...


xmlDictionary = [ XMLNode xmlToDictionary:rootNode ];


value = [ xmlDictionary valueForKeyPath:@"SearchResultArray.SearchResultItem" ]



I thought when the documentation said that NSXMLNode was kvc compliant that it would do this, but it didnt mean that it meant stuff like [ rootNode valueForKey:@"children" ] which is obvious really.

I also thought there must be a way to do the above, and there still might be, but I didnt find it.

I looked at using XPath and that is a solution. I also looked at applying an XSLT sheet against the XMLDoc and using that to convert to plist format and then reading that into NSDictionary. But I dont know XSLT and thought this was an interesting method to write.

I also wrote another category method nodeForPath:(NSString*)path that does a similar job but simply parses a path like "SearchResultItemArray.SearchResultItem" and produces the value on the fly. Actually its probably better to do it like that.

I'm experimenting with native NSXMLNode methods and my own ones to see which is easier and clearer to read.

No comments: