Fetch a XML feed and parse it into objects

Overview

AlamofireXmlToObjects

🚨 This is now a subspec of EVReflection and the code is maintained there. 🚨

You can install it as a subspec like this:

use_frameworks!
pod "EVReflection/AlamofireXML"

Besideds this subspec there are also subspecs for: XML, AlamofireXML, Moya, MoyaRxSwift and MoyaReflectiveSwift

Issues Documentation Stars Awesome

Version Language Platform Support License

Git Twitter ![LinkedIn](https://img.shields.io/badge/linkedin-Edwin Vermeer-blue.svg?style=flat) Website [eMail](mailto:[email protected]?SUBJECT=About AlamofireXmlToObjects)

If you have a question and don't want to create an issue, then we can Join the chat at https://gitter.im/evermeer/EVReflection (EVReflection is the base of AlamofireJsonToObjects)

With AlamofireXmlToObjects it's extremely easy to fetch a XML feed and parse it into objects. No property mapping is required. Reflection is used to put the values in the corresponding properties.

AlamofireXmlToObjects is based on the folowing libraries:

  • Alamofire is an elegant HTTP Networking library in Swift
  • XMLDictionary Is a simple way to parse and generate XML. Converts an XML file to an NSDictionary
  • EVReflection is used to parse the XML result to your objects

If you have a JSON service and want the same functionality then have a look at AlamofireJsonToObjects.

At this moment the master branch is for Swift3. If you want to continue using Swift 2.2 (or 2.3) then switch to the Swift2.2 branch. Run the tests to see AlamofireXmlToObjects in action.

Using AlamofireXmlToObjects in your own App

'AlamofireXmlToObjects' is available through the dependency manager CocoaPods.

You can just add AlamofireXmlToObjects to your workspace by adding the folowing 2 lines to your Podfile:

use_frameworks!
pod "AlamofireXmlToObjects"

You also have to add an import at the top of your swift file like this:

import AlamofireXmlToObjects

Sample code

class WeatherResponse: EVObject {
    var location: String?
    var three_day_forecast: [Forecast] = [Forecast]()
}

class Forecast: EVObject {
    var day: String?
    var temperature: NSNumber?
    var conditions: String?
}

class AlamofireXmlToObjectsTests {
    func testResponseObject() {
        let URL = "https://raw.githubusercontent.com/evermeer/AlamofireXmlToObjects/master/AlamofireXmlToObjectsTests/sample_xml"
        Alamofire.request(URL)
        .responseObject { (response: DataResponse<WeatherResponse>) in
            if let result = response.value {
               // That was all... You now have a WeatherResponse object with data
            }
        }
    }
}

The code above will parse the folowing XML into the objects:

<wheather>
   <location>Toronto, Canada</location>
   <three_day_forecast>
      <forecast>
         <conditions>Partly cloudy</conditions>
         <day>Monday</day>
         <temperature>20</temperature>
      </forecast>
      <forecast>
         <conditions>Showers</conditions>
         <day>Tuesday</day>
         <temperature>22</temperature>
      </forecast>
      <forecast>
         <conditions>Sunny</conditions>
         <day>Wednesday</day>
         <temperature>28</temperature>
      </forecast>
   </three_day_forecast>
</wheather>

Advanced object mapping

AlamofireJsonToObjects is based on EVReflection and you can use all EVReflection features like property mapping, converters, validators and key kleanup. See EVReflection for more information.

License

AlamofireXmlToObjects is available under the MIT 3 license. See the LICENSE file for more info.

My other libraries:

Also see my other open source iOS libraries:

  • EVReflection - Swift library with reflection functions with support for NSCoding, Printable, Hashable, Equatable and JSON
  • EVCloudKitDao - Simplified access to Apple's CloudKit
  • EVFaceTracker - Calculate the distance and angle of your device with regards to your face in order to simulate a 3D effect
  • EVURLCache - a NSURLCache subclass for handling all web requests that use NSURLReques
  • AlamofireJsonToObject - An Alamofire extension which converts JSON response data into swift objects using EVReflection
  • AlamofireXmlToObject - An Alamofire extension which converts XML response data into swift objects using EVReflection and XMLDictionary
  • AlamofireOauth2 - A swift implementation of OAuth2 using Alamofire
  • EVWordPressAPI - Swift Implementation of the WordPress (Jetpack) API using AlamofireOauth2, AlomofireXmlToObjects and EVReflection (work in progress)
  • PassportScanner - Scan the MRZ code of a passport and extract the firstname, lastname, passport number, nationality, date of birth, expiration date and personal numer.
Comments
  • Unable to parse and extract data

    Unable to parse and extract data

    Hi Edwin,

    Here's a section of the file I'm trying to parse:

    <allgames>
    <StateProv stateprov_name="Arkansas" stateprov_id="AR">
    <game game_id="101" game_name="Powerball" update_time="WED 2016-06-01 23:00:34 EST">
    <lastdraw_date>06/01/2016</lastdraw_date>
    <lastdraw_numbers>23-30-33-40-69, Powerball: 12, Power Play: 5</lastdraw_numbers>
    <nextdraw_date>06/04/2016</nextdraw_date>
    <jackpot date="06/04/2016">110000000</jackpot>
    </game>
    <game game_id="113" game_name="MEGA Millions" update_time="FRI 2016-06-03 23:01:31 EST">
    <lastdraw_date>06/03/2016</lastdraw_date>
    <lastdraw_numbers>32-54-65-66-71, Mega Ball: 10, Megaplier: 3</lastdraw_numbers>
    <nextdraw_date>06/07/2016</nextdraw_date>
    <jackpot date="06/03/2016">251000000</jackpot>
    </game>
    <game game_id="132" game_name="Lucky For Life" update_time="THU 2016-06-02 22:54:02 EST">
    <lastdraw_date>06/02/2016</lastdraw_date>
    <lastdraw_numbers>11-19-36-37-42, Lucky Ball: 10</lastdraw_numbers>
    <nextdraw_date>06/06/2016</nextdraw_date>
    </game>
    <game game_id="AR1" game_name="Natural State Jackpot" update_time="FRI 2016-06-03 21:19:03 EST">
    <lastdraw_date>06/03/2016</lastdraw_date>
    <lastdraw_numbers>04-18-19-21-33</lastdraw_numbers>
    <nextdraw_date>06/04/2016</nextdraw_date>
    <jackpot date="06/04/2016">105000</jackpot>
    </game>
    <game game_id="ARD" game_name="Cash 4 Midday" update_time="FRI 2016-06-03 14:10:03 EST">
    <lastdraw_date>06/03/2016</lastdraw_date>
    <lastdraw_numbers>6-0-8-3</lastdraw_numbers>
    <nextdraw_date>06/04/2016</nextdraw_date>
    </game>
    <game game_id="ARB" game_name="Cash 3 Midday" update_time="FRI 2016-06-03 14:09:03 EST">
    <lastdraw_date>06/03/2016</lastdraw_date>
    <lastdraw_numbers>4-7-4</lastdraw_numbers>
    <nextdraw_date>06/04/2016</nextdraw_date>
    </game>
    <game game_id="ARC" game_name="Cash 4 Evening" update_time="FRI 2016-06-03 20:10:02 EST">
    <lastdraw_date>06/03/2016</lastdraw_date>
    <lastdraw_numbers>2-6-4-1</lastdraw_numbers>
    <nextdraw_date>06/04/2016</nextdraw_date>
    </game>
    <game game_id="ARA" game_name="Cash 3 Evening" update_time="FRI 2016-06-03 20:12:12 EST">
    <lastdraw_date>06/03/2016</lastdraw_date>
    <lastdraw_numbers>5-2-0</lastdraw_numbers>
    <nextdraw_date>06/04/2016</nextdraw_date>
    </game>
    </StateProv>
    

    Some sections of my code:

    import UIKit
    
    import Alamofire
    
    import AlamofireXmlToObjects
    
    import ObjectMapper
    
    import AlamofireObjectMapper
    
    import EVReflection
    
    class LotteryResponse: EVObject {
    
            var stateprov_name: String?
    
            var gameData: [game] = [game]()
    
        }
    
     class game: EVObject {
    
            var game_name: String?
    
            var lastdraw_date: String?
    
            var lastdraw_numbers: String?
    
            var nextdraw_date: String?
    
            var jackpot: String?
    
        }
    
        class AlamofireXmlToObjects {
            func responseObject() {
                let urlString = "http://www.lotterynumbersxml.com/lotterydata/[email protected]/kjw8uwe/lottery_us.xml"
    
                Alamofire.request(.GET, urlString, parameters: nil)
                    .responseObject { (response: Result< LotteryResponse, NSError>) in
                        if let LotteryResponse = response.value {
    
                        }
                }
    
            }
        }
    
    
    question Solved? 
    opened by FasterThanLlamas 24
  • Cannot invoke 'responseObject ' with argument list of type '((WeatherResponse?,NSError?) -> ())'

    Cannot invoke 'responseObject ' with argument list of type '((WeatherResponse?,NSError?) -> ())'

    Hey,

    I would really like to use your CocoaPod but I can't get it to work. Even the sample code won't work. Any suggestions why this error is popping up ?

    opened by aosterthun 9
  • fatal error: NSArray element failed to match the Swift Array Element type

    fatal error: NSArray element failed to match the Swift Array Element type

    Hi,

    I'm trying to parse the following XML document:

    <channel name="HMIP-SWDO 0000D3C98C9E08:0" ise_id="1281" visible="true" operate="true">
    <datapoint name="HmIP-RF.0000D3C98C9E08:0.CONFIG_PENDING" type="CONFIG_PENDING" ise_id="1282" value="" valuetype="2" valueunit="" timestamp="0" operations="0"/>
    <datapoint name="HmIP-RF.0000D3C98C9E08:0.DUTY_CYCLE" type="DUTY_CYCLE" ise_id="1286" value="false" valuetype="2" valueunit="" timestamp="1472726147" operations="5"/>
    <datapoint name="HmIP-RF.0000D3C98C9E08:0.ERROR_CODE" type="ERROR_CODE" ise_id="1287" value="0" valuetype="8" valueunit="" timestamp="1472726147" operations="5"/>
    <datapoint name="HmIP-RF.0000D3C98C9E08:0.LOW_BAT" type="LOW_BAT" ise_id="1288" value="false" valuetype="2" valueunit="" timestamp="1472726147" operations="5"/>
    <datapoint name="HmIP-RF.0000D3C98C9E08:0.OPERATING_VOLTAGE" type="OPERATING_VOLTAGE" ise_id="1292" value="1.300000" valuetype="4" valueunit="" timestamp="1472726147" operations="5"/>
    <datapoint name="HmIP-RF.0000D3C98C9E08:0.SABOTAGE" type="SABOTAGE" ise_id="1293" value="false" valuetype="2" valueunit="" timestamp="1472726147" operations="5"/>
    <datapoint name="HmIP-RF.0000D3C98C9E08:0.UNREACH" type="UNREACH" ise_id="1297" value="false" valuetype="2" valueunit="" timestamp="1472726147" operations="5"/>
    </channel>
    <channel name="HMIP-SWDO 0000D3C98C9E08:1" ise_id="1301" visible="true" operate="true">
    <datapoint name="HmIP-RF.0000D3C98C9E08:1.STATE" type="STATE" ise_id="1302" value="0" valuetype="16" valueunit="""" timestamp="1472726147" operations="5"/>
    </channel>
    

    When I parse it with AlamofireXMLToObjects it throws fatal error: NSArray element failed to match the Swift Array Element type when there only is one child for the channel like here:

    <channel name="HMIP-SWDO 0000D3C98C9E08:1" ise_id="1301" visible="true" operate="true">
    <datapoint name="HmIP-RF.0000D3C98C9E08:1.STATE" type="STATE" ise_id="1302" value="0" valuetype="16" valueunit="""" timestamp="1472726147" operations="5"/>
    </channel>
    
    datapoint   [annHomeAutomation.HMDatapoint] 1 value 
    [0] __NSDictionaryM *   7 key/value pairs   0x00007f8f59f717e0
    [0] (null)  @"_value" : (no summary)    
    [1] (null)  @"_name" : @"HmIP-RF.0000D3C98C9E08:1.STATE"    
    [2] (null)  @"_ise_id" : (no summary)   
    [3] (null)  @"_type" : (no summary) 
    [4] (null)  @"_valueunit" : (no summary)    
    [5] (null)  @"_valuetype" : (no summary)    
    [6] (null)  @"_timestamp" : @"1472726457"
    

    for some reason it reads out the data but won't create the desired HMDatapoint object.

    opened by aosterthun 6
  • "not key value encoding-compliant" problem

    I have hit this problem with a new API XML feed.

    2016-04-12 13:35:29.178 Vault[55707:19474924]
    WARNING: The class 'XXX' is not key value coding-compliant for the key '__name' There is no support for optional type, array of optionals or enum properties. As a workaround you can implement the function 'setValue forUndefinedKey' for this. See the unit tests for more information

    previously, working with a different API (Json) and your AlamofireJsonToObjects library I solved the same problem by defining all the Json keys and also following your advice to add

    override internal func propertyMapping() -> [(String?, String?)] {
            return [("ignoredProperty",nil), ("propertyInObject","keyInJson")]
    }
    

    I am now stuck on this XML feed API and using AlamofireXmlToObjects, since it seems to generate some internal values I don't recognise from the API docs (_name, _version, _copyright) and there are also quite a few keys I would prefer to ignore

    Adding the propertyMapping() override as above doesn't help -- I noticed the final parameter is "keyInJson".

    Would appreciate any advice you might have with this

    question Solved? 
    opened by ghost 4
  • swift 3 issue

    swift 3 issue

    It does not look like this project has been converted to Swift 3. I tried letting Xcode 8 do the conversion but resulted in about 30 compiler errors.

    opened by hanssl 2
  •   Issue - #4, Unable to Parse

    Issue - #4, Unable to Parse

    Hi Evermeer,

    The XML Response that I sent you wrong, there was a mistake while copy paste. Sorry for wasting your time and energy. Here is the correct XML.

    <requestl> <qlist> <piname>MONTY CHICOLA</piname> <picell>318-730-5705</picell> <pihome>318-442-3893</pihome> <rinum>FAAAAANI</rinum> <dev>$00046728</dev> <riapt>KFOE</riapt> <rifbo>00001</rifbo> <ridatr>08/04/2016 07:06</ridatr> <ridats/> <riacft>N2244</riacft> <riftyp>AVGAS</riftyp> <rifunt>GAL</rifunt> <rifuel>0</rifuel> </qlist> <qlist> <piname>MONTY CHICOLA</piname> <picell>318-730-5705</picell> <pihome>318-442-3893</pihome> <rinum>FAAAAANL</rinum> <dev>$00046728</dev> <riapt>KFOE</riapt> <rifbo>00001</rifbo> <ridatr>08/04/2016-18:58</ridatr> <ridats/> <riacft>N55MC</riacft> <riftyp>AVGAS</riftyp> <rifunt>GAL</rifunt> <rifuel>00100</rifuel> </qlist> <qlist> <piname>MONTY CHICOLA</piname> <picell>318-730-5705</picell> <pihome>318-442-3893</pihome> <rinum>FAAAAANM</rinum> <dev>$00046728</dev> <riapt>KAEX</riapt> <rifbo>00001</rifbo> <ridatr>08/04/2016-19:01</ridatr> <ridats/> <riacft>N5JT</riacft> <riftyp>JET/A</riftyp> <rifunt>GAL</rifunt> <rifuel>100</rifuel> </qlist> <qlist> <piname>MONTY CHICOLA</piname> <picell>318-730-5705</picell> <pihome>318-442-3893</pihome> <rinum>FAAAAANN</rinum> <dev>$00046728</dev> <riapt>KAEX</riapt> <rifbo>00001</rifbo> <ridatr>08/04/2016-19:06</ridatr> <ridats/> <riacft>N2244</riacft> <riftyp>AVGAS</riftyp> <rifunt>GAL</rifunt> <rifuel>0</rifuel> </qlist> </requestl>

    Also I have a class containing all the properties under qlist. What I want is that the properties under qlist to be parsed as an object of the class. Please help me out with this. Thanks in advance.

    opened by manish-1612 1
  • Unable to Parse

    Unable to Parse

    I am trying to parse a XML which looks like this :

    <requestl> <qlist> <piname>MONTY CHICOLA</piname> <picell>318-730-5705</picell> <pihome>318-442-3893</pihome> <rinum>FAAAAAM7</rinum> <dev>$00046728</dev> <riapt>KFOE</riapt> <rifbo>00001</rifbo> <ridatr>08/02/2016-03:05</ridatr> <ridats/> <riacft>N5WF</riacft> <riftyp>JET/A</riftyp> <rifunt>GAL</rifunt> <rifuel>46549</rifuel> <xifptx/> <rifpt>05990</rifpt> <xifpsx/> <rifps>09990</rifps> <riinf1>SHELL 15 W 50</riinf1> <riinf2/> <ritarr>03:03</ritarr> <ridata>08/02/2016</ridata> <ridumd>08/02/2016 03:03</ridumd> <risort>20160802 20160802</risort> <ridumy>08/02/2016 03:03</ridumy> <ritdep>03:03</ritdep> <riddat>08/02/2016</riddat> <rinotr>N</rinotr> <rinotc>N</rinotc> <rinots>*</rinots> <ripdrp>0</ripdrp> <rippck>0</rippck> <riex2/> <xifpmx/> <rifpm>09960</rifpm> <xifpax/> <rifpa>90999</rifpa> <xifpix/> <rifpi>99990</rifpi> <xifpox/> <rifpo>00999</rifpo> <rihang/> <ristat>New Request</ristat> <rirepy/> <riext1>Crew Car</riext1> <riex1>N</riex1> <paname>CESSNA</paname> <pamodl>550</pamodl> <pafuel>AVGAS</pafuel> <riinst/> <riloc>H-1</riloc> <rifpum>00000</rifpum> <ritpum/> <riqoil>940</riqoil> <ritoil>SHELL 15 W 50</ritoil> <riusro/> <riapu/> <fbnam>Forbes Million Air</fbnam> <fbadd1>Forbes Field Bldg 610</fbadd1> <fbphon>877-862-0950</fbphon> <fbnam>Forbes Million Air</fbnam> </qlist> </requestl>

    I am not able to parse and extract data. Can you please help me out. Thank You

    opened by manish-1612 1
Releases(2.1.0)
Owner
Edwin Vermeer
Edwin Vermeer
Create or parse CoreData managed object model XMLs

MomXML Create or parse CoreData managed object model XMLs. Project description Model Contains struct objects which describe each XML elements. var mom

Eric Marchand 5 Aug 27, 2021
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

Marko Tadić 975 Dec 26, 2022
CheatyXML is a Swift framework designed to manage XML easily

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'

Louis Bodart 24 Mar 31, 2022
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 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
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
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
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
Convert text with HTML tags, links, hashtags, mentions into NSAttributedString. Make them clickable with UILabel drop-in replacement.

Convert text with HTML tags, links, hashtags, mentions into NSAttributedString. Make them clickable with UILabel drop-in replacement.

Pavel Sharanda 1.1k Dec 26, 2022
Swift package to convert a HTML table into an array of dictionaries.

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

null 1 Jun 18, 2022
Mathias KΓΆhnke 1.1k Dec 16, 2022
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.

Nicholas Bellucci 12 Sep 22, 2022
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

Nabil Chatbi 3.7k Jan 6, 2023
Pick a date and explore websites from the early days of the internet to now all in an easy-to-use browser format! πŸ’»

Pick a date and explore websites from the early days of the internet to now all in an easy-to-use browser format! ??

Liam 5 Nov 26, 2022
Securely synchronize any CareKit 2.1+ based app to a Parse Server Cloud. Compatible with parse-hipaa.

ParseCareKit Use at your own risk. There is no promise that this is HIPAA compliant and we are not responsible for any mishandling of your data This f

Network Reconnaissance Lab 31 Nov 24, 2022
This is an Instagram clone with a custom Parse backend that allows a user to post photos, view a global photos feed, and add comments!

Parstagram - Part II This is an Instagram clone with a custom Parse backend that allows a user to post photos, view a global photos feed, and add comm

Jose G Caudillo 0 Oct 30, 2021