• Stars
    star
    1,139
  • Rank 40,911 (Top 0.9 %)
  • Language
    Objective-C
  • License
    Other
  • Created over 13 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

[DEPRECATED]

WARNING: THIS PROJECT IS DEPRECATED

It will not receive any future updates or bug fixes. If you are using it, please migrate to another solution.


Purpose

XMLDictionary is a class designed to simplify parsing and generating of XML on iOS and Mac OS. XMLDictionary is built on top of the NSXMLParser classes, but behaves more like a DOM-style parser rather than SAX parser, in that it creates a tree of objects rather than generating events at the start and end of each node.

Unlike other DOM parsers, XMLDictionary does not attempt to replicate all of the nuances of the XML standard such as the ability to nest tags within text. If you need to represent something like an HTML document then XMLDictionary won't work for you. If you want to use XML as a data interchange format for passing nested data structures then XMLDictionary may well provide a simpler solution than other DOM-based parsers.

Supported OS & SDK Versions

  • Supported build target - iOS 10.2 / Mac OS 10.12 (Xcode 8.2, Apple LLVM compiler 8.0)
  • Earliest supported deployment target - iOS 8.0 / Mac OS 10.10
  • Earliest compatible deployment target - iOS 4.3 / Mac OS 10.6

NOTE: 'Supported' means that the library has been tested with this version. 'Compatible' means that the library should work on this OS version (i.e. it doesn't rely on any unavailable SDK features) but is no longer being tested for compatibility and may require tweaking or bug fixes to run correctly.

ARC Compatibility

As of version 1.1, XMLDictionary requires ARC. If you wish to use XMLDictionary in a non-ARC project, just add the -fobjc-arc compiler flag to the XMLDictionary.m class. To do this, go to the Build Phases tab in your target settings, open the Compile Sources group, double-click XMLDictionary.m in the list and type -fobjc-arc into the popover.

If you wish to convert your whole project to ARC, comment out the #error line in XMLDictionary.m, then run the Edit > Refactor > Convert to Objective-C ARC... tool in Xcode and make sure all files that you wish to use ARC for (including XMLDictionary.m) are checked.

Thread Safety

XMLDictionary's methods should all be thread safe. It is safe to use multiple XMLDictionaryParsers concurrently on different threads, but it is not safe to call the same parser concurrently on multiple threads.

Installation

To use the XMLDictionary in an app, just drag the class files into your project.

XMLDictionaryParser

The XMLDictionaryParser class is responsible for parsing an XML file into a dictionary. You don't normally need to use this class explicitly as you can just use the utility methods added to NSDictionary, however it can be useful if you want to modify the default parser settings.

You can create new instances of XMLDictionaryParser if you need to use multiple different settings for different dictionaries. Once you have created an XMLDictionaryParser you can use the following methods to parse XML files using that specific parser instance:

- (NSDictionary *)dictionaryWithData:(NSData *)data;
- (NSDictionary *)dictionaryWithString:(NSString *)string;
- (NSDictionary *)dictionaryWithFile:(NSString *)path;
- (NSDictionary *)dictionaryWithParser:(NSXMLParser *)parser;

Alternatively, you can simply modify the settings of [XMLDictionaryParser sharedInstance] to affect the settings for all dictionaries parsed subsequently using the NSDictionary category extension methods.

Use the following properties to tweak the parsing behaviour:

@property (nonatomic, assign) BOOL collapseTextNodes;

If YES (the default value), tags that contain only text and have no children, attributes or comments will be collapsed into a single string object, simplifying traversal of the object tree.

@property (nonatomic, assign) BOOL stripEmptyNodes;

If YES (the default value), tags that are empty (have no children, attributes, text or comments) will be stripped.

@property (nonatomic, assign) BOOL trimWhiteSpace;

If YES (the default value), leading and trailing white space will be trimmed from text nodes, and text nodes containing only white space will be omitted from the dictionary.

@property (nonatomic, assign) BOOL alwaysUseArrays;

If YES, the every child node will be represented as an array, even if there is only one of them. This simplifies the logic needed to cope with properties that may be duplicated because you don't need to use [value isKindOfClass:[NSArray class]] to check the for the singular case. Defaults to NO.

@property (nonatomic, assign) BOOL preserveComments;

If YES, XML comments will be grouped into an array under the key __comments and can be accessed via the comments method. Defaults to NO.

@property (nonatomic, assign) XMLDictionaryAttributesMode attributesMode;

This property controls how XML attributes are handled. The default is XMLDictionaryAttributesModePrefixed meaning that attributes will be included in the dictionary, with an _ (underscore) prefix to avoid namespace collisions. Alternative values are XMLDictionaryAttributesModeDictionary, which will place all the attributes in a separate dictionary, XMLDictionaryAttributesModeUnprefixed, which includes the attributes without prefix (which may cause collisions with nodes) and XMLDictionaryAttributesModeDiscard, which will strip the attributes.

@property (nonatomic, assign) XMLDictionaryNodeNameMode nodeNameMode;

This property controls how the node name is handled. The default value is XMLDictionaryNodeNameModeRootOnly, meaning that the node name will only be included in the root dictionary (the names for the children can be inferred from the dictionary keys, but the nodeName method won't work for anything except the root node). Alternative values are XMLDictionaryNodeNameModeAlways, meaning that the node name will be included in the dictionary with the key __name (and can be accessed using the nodeName) method, or XMLDictionaryNodeNameModeNever which will never include the `__name' key.

Category Methods

XMLDictionary extends NSDictionary with the following methods:

  • (NSDictionary *)dictionaryWithXMLParser:(NSParser *)parser;

Create a new NSDictionary object from an existing NSXMLParser. Useful if fetching data through AFNetworking.

+ (NSDictionary *)dictionaryWithXMLData:(NSData *)data;

Create a new NSDictionary object from XML-encoded data.

+ (NSDictionary *)dictionaryWithXMLString:(NSString *)string;

Create a new NSDictionary object from XML-encoded string.

+ (NSDictionary *)dictionaryWithXMLFile:(NSString *)path;

Create a new NSDictionary object from and XML-encoded file.

- (NSString *)attributeForKey:(NSString *)key;

Get the XML attribute for a given key (key name should not include prefix).

- (NSDictionary *)attributes;

Get a dictionary of all XML attributes for a given node's dictionary. If the node has no attributes then this will return nil.

- (NSDictionary *)childNodes;

Get a dictionary of all child nodes for a given node's dictionary. If multiple nodes have the same name they will be grouped into an array. If the node has no children then this will return nil.

- (NSArray *)comments;

Get an array of all comments for a given node. Note that the nesting relative to other nodes is not preserved. If the node has no comments then this will return nil.

- (NSString *)nodeName;

Get the name of the node. If the name is not known this will return nil.

- (NSString *)innerText;

Get the text content of the node. If the node has no text content, this will return nil;

- (NSString *)innerXML;

Get the contents of the node as an XML-encoded string. This XML string will not include the container node itself.

- (NSString *)XMLString;

Get the node and its content as an XML-encoded string. If the node name is not known, the top level tag will be called <root>.

- (NSArray *)arrayValueForKeyPath:(NSString *)keyPath;

Works just like valueForKeyPath: except that the value returned will always be an array. So if there is only a single value, it will be returned as @[value].

- (NSString *)stringValueForKeyPath:(NSString *)keyPath;

Works just like valueForKeyPath: except that the value returned will always be a string. So if the value is a dictionary, the text value of innerText will be returned, and if the value is an array, the first item will be returned.

- (NSDictionary *)dictionaryValueForKeyPath:(NSString *)keyPath;

Works just like valueForKeyPath: except that the value returned will always be a dictionary. So if the collapseTextNodes option is enabled and the value is a string, this will convert it back to a dictionary before returning, and if the value is an array, the first item will be returned.

Usage

The simplest way to load an XML file is as follows:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"someFile" ofType:@"xml"];
NSDictionary *xmlDoc = [NSDictionary dictionaryWithXMLFile:filePath];

You can then iterate over the dictionary as you would with any other object tree, e.g. one loaded from a Plist.

To access nested nodes and attributes, you can use the valueForKeyPath syntax. For example to get the string value of <foo> from the following XML:

<root>
	<bar cliche="true">
		<foo>Hello World</foo>
	</bar>
	<banjo>Was his name-oh</banjo>
</root>

You would write:

NSString *foo = [xmlDoc valueForKeyPath:@"bar.foo"];

The above examples assumes that you are using the default setting for collapseTextNodes and alwaysUseArrays. If collapseTextNodes is disabled then you would instead access <foo>'s value by writing:

NSString *foo = [[xmlDoc valueForKeyPath:@"bar.foo"] innerText];

If the alwaysUseArrays option is enabled then would use one of the following, depending on the collapseTextNodes property:

NSString *foo = [[xmlDoc valueForKeyPath:@"bar.foo"] firstObject];
NSString *foo = [[[xmlDoc valueForKeyPath:@"bar.foo"] firstObject] innerText];

To get the cliche attribute of bar, you could write:

NSString *barCliche = [xmlDoc[@"bar] attributes][@"cliche"];

If the attributesMode is set to the default value of XMLDictionaryAttributesModePrefixed then you can also do this:

NSString *barCliche = [xmlDoc valueForKeyPath:@"bar._cliche"];

Or if it is set to XMLDictionaryAttributesModeUnprefixed you would simply do this:

NSString *barCliche = [xmlDoc valueForKeyPath:@"bar.cliche"];

Release Notes

Version 1.4.1

  • Upgraded for Xcode 8.2
  • Added tvOS and watchOS support to podspec

Version 1.4

  • Added dictionaryWithXMLParser: constructor method
  • Added wrapRootNode option as a nicer way to preserve root node name
  • No longer crashes if non-string values are used as keys or attributes
  • Now complies with the -Weverything warning level

Version 1.3

  • added stripEmptyNodes property (defaults to YES)
  • added arrayValueForKeyPath, stringValueForKeyPath and dictionaryValueForKeyPath methods to simplify working with data

Version 1.2.2

  • sharedInstance method no longer returns a new instance each time

Version 1.2.1

  • Removed isa reference, deprecated in iOS 7

Version 1.2

  • Exposed XMLDictionaryParser object, which can be used to configure the parser
  • Parsing options can now be changed without modifying the library
  • Added option to always encode properties as arrays
  • __name and __coment keys are no longer included by default
  • Apostrophe is now encoded as &apos;
  • removed attributeForKey: method

Version 1.1

  • Updated to use ARC
  • Added podspec

Version 1.0

  • Initial release

More Repositories

1

iCarousel

A simple, highly customisable, data-driven 3D carousel for iOS and Mac OS
Objective-C
11,999
star
2

SwiftFormat

A command-line tool and Xcode Extension for formatting Swift code
Swift
7,781
star
3

FXBlurView

[DEPRECATED]
Objective-C
4,942
star
4

iRate

[DEPRECATED]
Objective-C
4,100
star
5

FXForms

[DEPRECATED]
Objective-C
2,926
star
6

SwipeView

SwipeView is a class designed to simplify the implementation of horizontal, paged scrolling views on iOS. It is based on a UIScrollView, but adds convenient functionality such as a UITableView-style dataSource/delegate interface for loading views dynamically, and efficient view loading, unloading and recycling.
Objective-C
2,646
star
7

layout

A declarative UI framework for iOS
Swift
2,231
star
8

iVersion

[DEPRECATED]
Objective-C
1,947
star
9

NullSafe

NullSafe is a simple category on NSNull that returns nil for unrecognised messages instead of throwing an exception
Objective-C
1,943
star
10

RetroRampage

Tutorial series demonstrating how to build a retro first-person shooter from scratch in Swift
Swift
1,486
star
11

AutoCoding

AutoCoding is a category on NSObject that provides automatic support for NSCoding and NSCopying to every object.
Objective-C
1,068
star
12

GZIP

A simple NSData category for gzipping/unzipping data in iOS and Mac OS
Objective-C
983
star
13

FastCoding

A faster and more flexible binary file format replacement for NSCoding, Property Lists and JSON
C
976
star
14

AsyncImageView

[DEPRECATED]
Objective-C
906
star
15

iConsole

[DEPRECATED]
Objective-C
859
star
16

Expression

A cross-platform Swift library for evaluating mathematical expressions at runtime
Swift
822
star
17

FXLabel

[DEPRECATED]
Objective-C
816
star
18

CountryPicker

CountryPicker is a custom UIPickerView subclass that provides an iOS control allowing a user to select a country from a list. It can optionally display a flag next to each country name, and the library includes a set of 249 high-quality, public domain flag images from FAMFAMFAM (http://www.famfamfam.com/lab/icons/flags/) that have been painstakingly re-named by country code to work with the library.
Objective-C
740
star
19

Euclid

A Swift library for creating and manipulating 3D geometry
Swift
637
star
20

SoundManager

Simple sound and music player class for playing audio on Mac and iPhone
Objective-C
630
star
21

FXImageView

FXImageView is a class designed to simplify the application of common visual effects such as reflections and drop-shadows to images, and also to help the performance of image loading by handling it on a background thread.
Objective-C
628
star
22

Base64

[DEPRECATED]
Objective-C
578
star
23

FXKeychain

[DEPRECATED]
Objective-C
554
star
24

MustOverride

Provides a macro that you can use to ensure that a method of an abstract base class *must* be overriden by its subclasses.
Objective-C
523
star
25

LayerSprites

LayerSprites is a library designed to simplify the use of sprite sheets (image maps containing multiple sub-images) in UIKit applications without using OpenGL or 3rd-party game libraries. Can load sprite sheets in the Coco2D format.
Objective-C
504
star
26

GLView

[DEPRECATED]
Objective-C
477
star
27

FXNotifications

An alternative API for NSNotificationCenter that doesn't suck
Objective-C
392
star
28

ShapeScript

The ShapeScript 3D modeling app for macOS and iOS
Swift
391
star
29

LRUCache

LRUCache is an open-source replacement for NSCache that behaves in a predictable, debuggable way
Swift
378
star
30

VectorMath

A Swift library for Mac and iOS that implements common 2D and 3D vector and matrix functions, useful for games or vector-based graphics
Swift
367
star
31

ReflectionView

[DEPRECATED]
Objective-C
359
star
32

Swiftenstein

Simple Wolfenstein 3D clone written in Swift
Swift
359
star
33

JPNG

JPNG is a bespoke image file format that combines the compression benefits of JPEG with the alpha channel support of a PNG file. The JPNG library provides an Objective-C implementation of this format along with transparent JPNG loading support for iOS and Mac OS.
Objective-C
340
star
34

StandardPaths

StandardPaths is a category on NSFileManager for simplifying access to standard application directories on iOS and Mac OS and abstracting the iCloud backup flags on iOS. It also provides support for working with device-specific file suffixes, such as the @2x suffix for Retina displays, or the -568h suffix for iPhone 5 and can optionally swizzle certain UIKit methods to support these suffixes more consistently.
Objective-C
336
star
35

ViewUtils

ViewUtils is a collection of category methods designed that extend UIView with all the handy little properties and functionality that you always wished were built-in to begin with.
Objective-C
324
star
36

FXPageControl

Simple, drop-in replacement for the iPhone UIPageControl that allows customisation of the dot colour, size and spacing.
Objective-C
298
star
37

BaseModel

BaseModel provides a base class for building model objects for your iOS or Mac OS projects. It saves you the hassle of writing boilerplate code, and encourages good practices by reducing the incentive to cut corners in your model implementation.
Objective-C
288
star
38

OrderedDictionary

This library provides OrderedDictionary and MutableOrderedDictionary subclasses.
Objective-C
278
star
39

ColorUtils

[DEPRECATED]
Objective-C
256
star
40

Tribute

A command-line tool for tracking Swift project licenses
Swift
246
star
41

OSNavigationController

[DEPRECATED]
Objective-C
233
star
42

Consumer

Mac and iOS library for parsing structured text
Swift
226
star
43

iNotify

[DEPRECATED]
Objective-C
225
star
44

FPSControls

An experimental implementation of touch-friendly first-person shooter controls using SceneKit and Swift
Swift
215
star
45

OSCache

OSCache is an open-source re-implementation of NSCache that behaves in a predictable, debuggable way.
Objective-C
200
star
46

Chess

A simple Chess game for iOS, written in Swift
Swift
177
star
47

RequestQueue

[DEPRECATED]
Objective-C
174
star
48

FXReachability

Lightweight reachability class for Mac and iOS
Objective-C
173
star
49

Sprinter

A library for formatting strings on iOS and macOS
Swift
166
star
50

CryptoCoding

CryptoCoding is a superset of the NSCoding protocol that allows for simple, seamless AES encryption of any NSCoding-compatible object.
Objective-C
148
star
51

RequestUtils

A collection of category methods designed to simplify the process of HTTP request construction and manipulation in Cocoa.
Objective-C
142
star
52

CubeController

CubeController is a UIViewController subclass that can be used to create a rotating 3D cube navigation.
Objective-C
142
star
53

HTMLLabel

[DEPRECATED]
Objective-C
139
star
54

NSOperationStack

[DEPRECATED]
Objective-C
118
star
55

SVGPath

Cross-platform Swift library for parsing SVGPath strings
Swift
111
star
56

HRCoder

HRCoder is a replacement for the NSKeyedArchiver and NSKeyedUnarchiver classes that uses a human-readable/editable format that can easily be stored in a regular Plist or JSON file.
Objective-C
104
star
57

iPrompt

[DEPRECATED]
Objective-C
99
star
58

Presentations

Code samples and projects for presentations that I have given
Objective-C
98
star
59

FXPhotoEditView

[DEPRECATED]
Objective-C
92
star
60

StackView

StackView is a class designed to simplify the implementation of vertical stacks of views on iOS. You can think of it as a bit like a simplified version of UITableView.
Objective-C
73
star
61

WebContentView

[DEPRECATED]
Objective-C
69
star
62

StringCoding

StringCoding is a simple Mac/iOS library for setting object properties of any type using string values. It can automatically detect the property type and attempt to interpret the string as the right kind of value. It's particularly oriented towards iOS app theming (see README for details).
Objective-C
57
star
63

ArrayUtils

[DEPRECATED]
Objective-C
49
star
64

Swune

Swift/UIKit reimplementation of the Dune II RTS game
Swift
46
star
65

Parsing

Supporting code for my talk entitled "Parsing Formal Languages with Swift"
Swift
42
star
66

MACAddress

[DEPRECATED]
Objective-C
39
star
67

FXParser

[DEPRECATED]
Objective-C
34
star
68

RotateView

Objective-C
34
star
69

RandomSequence

A class for creating independent, repeatable pseudorandom number sequences on Mac and iOS
Objective-C
28
star
70

FloatyBalloon

This is the source code for a simple game called Floaty Balloon, based on the gameplay of Flappy Bird. It was created as a tutorial for http://iosdevelopertips.com
Objective-C
25
star
71

Concurrency

Full source code for a simple currency calculator app
Objective-C
15
star
72

FXJSON

[DEPRECATED]
Objective-C
15
star
73

PNGvsJPEG

This is a simple benchmark app to compare JPEG vs PNG loading performance on iOS. Spoiler: JPEG wins.
Objective-C
6
star