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. &gt; to > or &lt; 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)

3 Responses to “Unescaping XML Entities in NSStrings”

  1. Johnnie Walker Says:

    I think the disk image link might be broken. Anyone have a working link?

  2. Johnnie Walker Says:

    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/

  3. Bin Says:

    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

Leave a Reply