CheatyXML is a Swift framework designed to manage XML easily

Overview

CheatyXML

CocoaPods Build Status codecov

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:

import CheatyXML

Usage

Let's take the following XML content for all of our examples:

<blog version="1.0" creator="lobodart">
    <name>MyAwesomeBlog!</name>
    <users>
        <admin is_active="true">lobodart</admin>
        <moderator is_active="false">slash705</moderator>
        <moderator is_active="...">...</moderator>
        ...
    </users>
    <article>
        <title>My first article</title>
        <description>This is the first article</description>
        <infos>
            <date>2015-03-15 15:42:42</date>
            <rate>42</rate>
        </infos>
        ...
    </article>
    <article>
        ...
    </article>
    ...
</blog>

Creating parser instance

Using an URL
let parser: CXMLParser! = CXMLParser(contentsOfURL: ...) // URL
Using a string
let parser: CXMLParser! = CXMLParser(string: ...) // String
Using data
let parser: CXMLParser! = CXMLParser(data: ...) // Data

Retrieving an element using tags

Suppose we want to retrieve the name of our example:

let blogName: String! = parser["name"].stringValue // Returns a String
let blogName: String? = parser["name"].string // Returns an optional String

You can also use the rootElement if you to make your code clearer:

let element = parser.rootElement["name"] // is the same as the notation seen before

To access deeper elements, just chain :

let blogAdmin: String! = parser["users"]["admin"].stringValue
print(blogAdmin) // lobodart

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:

let firstArticleTitle: String! = parser["article", 0]["title"].stringValue
let firstArticleTitle: String! = parser["article"][0]["title"].stringValue

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:

for element in parser.rootElement {
    print(element.tagName)
}

This code will give us :

name
users
article
article
...

Now, to iterate over specific children of an element, the code is almost the same:

for element in parser.rootElement.elementsNamed("article") {
    print(element.tagName)
}

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:

// Suppose we have 3 moderators in our example
let numberOfElements: Int = parser["users"].numberOfChildElements
print(numberOfElements) // 4 (3 moderators + 1 admin)

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:

let numberOfElements: Int = parser["users"]["moderator"].count
let numberOfElements: Int = parser["users"].elementsNamed("moderator").count

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.

let firstArticleRate = parser["article", 0]["rate"]
firstArticleRate.int // Optional(42)
firstArticleRate.intValue // 42
firstArticleRate.float // Optional(42.0)
firstArticleRate.floatValue // 42.0

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.

let firstArticleTitle = parser["article", 0]["title"]
firstArticleTitle.string // Optional("My first article")
firstArticleTitle.stringValue // "My first article"
firstArticleTitle.int // nil
firstArticleTitle.intValue // 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:

let articleDate: String! = parser["article", 0]["infos"]["date"].stringValue
print(articleDate) // 2015-03-15 15:42:42
let articleDateFail: String! = parser["articles", 0]["infos"]["date"].string // I intentionally add an 's' to 'article'
print(articleDateFail) // nil
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

let blogVersion = parser.rootElement.attribute("version")
let adminIsActive = parser["users"]["admin"].attribute("is_active")

You can also use the type casting on attributes:

let blogVersion = parser.rootElement.attribute("version").floatValue // 1.0
let creator = parser.rootElement.attribute("creator").stringValue // "lobodart"

Get all

let attributes = parser.rootElement.attributes // Will give you a [CXMLAttribute]
let dic = attributes.dictionary // Will give you a [String: String]

TO-DO

  • Add more Unit Tests
  • Class mapping
  • XML Generator
You might also like...
Fetch a XML feed and parse it into objects

AlamofireXmlToObjects ๐Ÿšจ This is now a subspec of EVReflection and the code is maintained there. ๐Ÿšจ You can install it as a subspec like this: use_fra

WKZombie is a Swift framework for iOS/OSX to navigate within websites and collect data without the need of User Interface or API, also known as Headless browser. It can be used to run automated tests / snapshots and manipulate websites using Javascript. An Objective-C framework for your everyday HTML needs.
An Objective-C framework for your everyday HTML needs.

HTMLKit An Objective-C framework for your everyday HTML needs. Quick Overview Installation Parsing The DOM CSS3 Selectors Quick Overview HTMLKit is a

SwiftSoup: Pure Swift HTML Parser, with best of DOM, CSS, and jquery (Supports Linux, iOS, Mac, tvOS, watchOS)
SwiftSoup: Pure Swift HTML Parser, with best of DOM, CSS, and jquery (Supports Linux, iOS, Mac, tvOS, watchOS)

SwiftSoup is a pure Swift library, cross-platform (macOS, iOS, tvOS, watchOS and Linux!), for working with real-world HTML. It provides a very conveni

๐Ÿ“„ A Swift DSL for writing type-safe HTML/CSS in SwiftUI way

๐Ÿ“„ swift-web-page (swep) Swep is a Swift DSL for writing type-safe HTML/CSS in SwiftUI way. Table of Contents Motivation Examples Safety Design FAQ In

Swift package to convert a HTML table into an array of dictionaries.

Swift package to convert a HTML table into an array of dictionaries.

Mongrel is a Swift and HTML hybrid with a bit of support for CSS and Javascript.

Mongrel is a Swift and HTML hybrid with a bit of support for CSS and Javascript. Using a declaritive style of programming, Mongrel makes writing HTML feel natural and easy. Mongrel also uses a SwiftUI like body structure allowing structs to be completely dedicated as an HTML page or element.

Easily Manage Graphics in Xcode Projects
Easily Manage Graphics in Xcode Projects

Introduction Challenges Managing Graphic Assets Manually Create Multiple Sizes Store Generated Image Files What If You Had... Care-Free Graphic Manage

A camera designed in Swift for easily integrating CoreML models - as well as image streaming, QR/Barcode detection, and many other features
A camera designed in Swift for easily integrating CoreML models - as well as image streaming, QR/Barcode detection, and many other features

Would you like to use a fully-functional camera in an iOS application in seconds? Would you like to do CoreML image recognition in just a few more sec

Mockingbird was designed to simplify software testing, by easily mocking any system using HTTP/HTTPS
Mockingbird was designed to simplify software testing, by easily mocking any system using HTTP/HTTPS

Mockingbird Mockingbird was designed to simplify software testing, by easily mocking any system using HTTP/HTTPS, allowing a team to test and develop

Swift minion for simple and lightweight XML parsing

AEXML Swift minion for simple and lightweight XML parsing I made this for personal use, but feel free to use it or contribute. For more examples check

The most swifty way to deal with XML data in swift 5.

SwiftyXML SwiftyXML use most swifty way to deal with XML data. Features Infinity subscript dynamicMemberLookup Support (use $ started string to subscr

Simple XML parsing in Swift
Simple XML parsing in Swift

SWXMLHash SWXMLHash is a relatively simple way to parse XML in Swift. If you're familiar with NSXMLParser, this library is a simple wrapper around it.

Easy XML parsing using Codable protocols in Swift

XMLCoder Encoder & Decoder for XML using Swift's Codable protocols. This package is a fork of the original ShawnMoore/XMLParsing with more features an

A simple way to map XML to Objects written in Swift

XMLMapper XMLMapper is a framework written in Swift that makes it easy for you to convert your model objects (classes and structs) to and from XML. Ex

A fast & lightweight XML & HTML parser in Swift with XPath & CSS support

Fuzi (ๆ–งๅญ) A fast & lightweight XML/HTML parser in Swift that makes your life easier. [Documentation] Fuzi is based on a Swift port of Mattt Thompson's

Ji (ๆˆŸ) is an XML/HTML parser for Swift
Ji (ๆˆŸ) is an XML/HTML parser for Swift

Ji ๆˆŸ Ji (ๆˆŸ) is a Swift wrapper on libxml2 for parsing XML/HTML. Features Build XML/HTML Tree and Navigate. XPath Query Supported. Comprehensive Unit T

Kanna(้‰‹) is an XML/HTML parser for Swift.

Kanna(้‰‹) Kanna(้‰‹) is an XML/HTML parser for cross-platform(macOS, iOS, tvOS, watchOS and Linux!). It was inspired by Nokogiri(้‹ธ). โ„น๏ธ Documentation Fea

Kanna(้‰‹) is an XML/HTML parser for Swift.

Kanna(้‰‹) Kanna(้‰‹) is an XML/HTML parser for cross-platform(macOS, iOS, tvOS, watchOS and Linux!). It was inspired by Nokogiri(้‹ธ). โ„น๏ธ Documentation Fea

Comments
  • Please, support tvOS

    Please, support tvOS

    Hi, is there a reason why can't u support tvOS. Tried to add your awesome pod and got this: [!] The platform of the target x (tvOS 13) is not compatible with CheatyXML (3.0.0), which does not support tvOS.

    opened by Maxatma 3
  • Swift-ier Code

    Swift-ier Code

    • Now taking advantage of Swift 2 features like guard
    • Removed most internal implicit optionals as they were prone to crashes
    • Removed all external implicit optionals since XMLNullElement was already taking care of that
    • Reworked initโ€™s to drop the need for initXMLParser
    • Removed redundant private/public properties where possible
    • Restored description overrides
    • Minor performance improvement by making the NSRegularExpression object a class constant instead of creating everytime parser:foundCharacters: is called
    opened by shnhrrsn 1
Releases(v3.1.1)
Owner
Louis Bodart
Louis Bodart
The most swifty way to deal with XML data in swift 5.

SwiftyXML SwiftyXML use most swifty way to deal with XML data. Features Infinity subscript dynamicMemberLookup Support (use $ started string to subscr

Kevin 99 Sep 6, 2022
Simple XML parsing in Swift

SWXMLHash SWXMLHash is a relatively simple way to parse XML in Swift. If you're familiar with NSXMLParser, this library is a simple wrapper around it.

David Mohundro 1.3k Jan 3, 2023
Easy XML parsing using Codable protocols in Swift

XMLCoder Encoder & Decoder for XML using Swift's Codable protocols. This package is a fork of the original ShawnMoore/XMLParsing with more features an

Max Desiatov 657 Dec 30, 2022
A simple way to map XML to Objects written in Swift

XMLMapper XMLMapper is a framework written in Swift that makes it easy for you to convert your model objects (classes and structs) to and from XML. Ex

Giorgos Charitakis 109 Jan 6, 2023
A fast & lightweight XML & HTML parser in Swift with XPath & CSS support

Fuzi (ๆ–งๅญ) A fast & lightweight XML/HTML parser in Swift that makes your life easier. [Documentation] Fuzi is based on a Swift port of Mattt Thompson's

Ce Zheng 994 Jan 2, 2023
Ji (ๆˆŸ) is an XML/HTML parser for Swift

Ji ๆˆŸ Ji (ๆˆŸ) is a Swift wrapper on libxml2 for parsing XML/HTML. Features Build XML/HTML Tree and Navigate. XPath Query Supported. Comprehensive Unit T

HongHao Zhang 824 Dec 15, 2022
Kanna(้‰‹) is an XML/HTML parser for Swift.

Kanna(้‰‹) Kanna(้‰‹) is an XML/HTML parser for cross-platform(macOS, iOS, tvOS, watchOS and Linux!). It was inspired by Nokogiri(้‹ธ). โ„น๏ธ Documentation Fea

Atsushi Kiwaki 2.3k Dec 31, 2022
Simple XML Parser implemented in Swift

Simple XML Parser implemented in Swift What's this? This is a XML parser inspired by SwiftyJSON and SWXMLHash. NSXMLParser in Foundation framework is

Yahoo! JAPAN 531 Jan 1, 2023
A sensible way to deal with XML & HTML for iOS & macOS

Ono (ๆ–ง) Foundation lacks a convenient, cross-platform way to work with HTML and XML. NSXMLParser is an event-driven, SAX-style API that can be cumbers

Mattt 2.6k Dec 14, 2022
Generate styled SwiftUI Text from strings with XML tags.

XMLText is a mini library that can generate SwiftUI Text from a given XML string with tags. It uses AttributedString to compose the final text output.

null 15 Dec 7, 2022