CheatyXML
CheatyXML is a Swift framework designed to manage XML easily.
Requirements
- iOS 8.0 or later
- tvOS 9.0 or later
Installation
Cocoapods
If you're using cocoapods, just add pod 'CheatyXML'
into your Podfile
file.
Manual
To install this, simply add the .xcodeproj to your project, and do not forget to link the .framework.
Whenever you want to use it in your code, simply type:
Usage
Let's take the following XML content for all of our examples:
Creating parser instance
Using an URL
Using a string
Using data
Retrieving an element using tags
Suppose we want to retrieve the name
of our example:
You can also use the rootElement
if you to make your code clearer:
To access deeper elements, just chain :
Working with multiple elements
Now let's take a look at the article
element. We can see that our blog
contains a few articles.
Get an element using its index
If we want to get the title of the first article, we can do it like this:
Both notations have the same effect. Choose the one you like most.
Browse children of an element
To iterate over all children of an element, just use the for in
classic syntax:
This code will give us :
name
users
article
article
...
Now, to iterate over specific children of an element, the code is almost the same:
This time, it will give us :
article
article
...
Of course, you can use this method on any deeper elements (like users
for example).
Number of children of an element
If you want to get the total number of children contained in an element, you can use this code:
Note that this code counts all child elements contained in users
. Now suppose we want to get the number of moderators only. There are 2 different syntaxes. Once again, choose your favorite:
Type casting
CheatyXML allows you to cast tag/attribute values into some common types. You can get either optional or non-optional value for your cast.
If you are not sure about the type, use the optional cast. If you try to cast a value with an inappropriate caster, your app will crash.
Missing tags
Until now, we always retrieved existing tags but what would happen if a tag doesn't exist? Let's take an example:
Note
If you have any doubt, keep in mind that using .string
is safer than using .stringValue
. In the previous example, using .stringValue
on articleDateFail
will result in your application to crash.
Attributes
Get one
You can also use the type casting on attributes:
Get all
TO-DO
- [ ] Add more Unit Tests
- [ ] Class mapping
- [ ] XML Generator