Unescaping XML Entities in NSStrings
Ever find yourself wishing that NSString or NSXMLParser in Panther provided a quick and dirty way to unescape XML entities (e.g. > to > or < to <) in Cocoa strings? I recently worked on a personal Cocoa project that parses simple XML documents, and I often needed to convert the standard five XML entities to their literal values. Unfortunately, unless I’m really missing something (and it’s possible I am, since NSXMLParser isn’t exactly the most documented of Cocoa classes) this isn’t something you get without the use of a DTD in NSXMLParser—at least the attribute values I was dealing with exclusively were being returned by the parser with entities intact, and the various entity-related delegate methods were not being called.
Fortunately, I found a relatively easy solution to the problem: CFXMLCreateStringByUnescapingEntities(). This handy function will unescape the entities in a string using a provided mapping dictionary, or, if no mapping is provided, simply handle the standard five. For ease of use, I wrapped the function in a friendly Objective-C method and stuck it in a category on NSString, which I am posting here for the benefit of all mankind. Enjoy!
- NSString+XMLUtils.dmg (9k)
April 12th, 2005 at 5:10 am
I think the disk image link might be broken. Anyone have a working link?
April 12th, 2005 at 5:31 am
I found the relevant code in the CVS for the Cocoalicous Project as part of NSString+SFHFUtils:
http://cvs.sourceforge.net/viewcvs.py/cocoalicious/cocoalicious/Utilities/
May 9th, 2005 at 12:26 am
Hi,
I searched NSXmlParser and found your blog. Unfortunately, the above link to the dmg file does not work. Could you please send me your program to study? Thank you