A simple way to map XML to Objects written in Swift

Overview

XMLMapper

CI Status Version License Platform Swift Package Manager compatible Carthage compatible

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.

Example

To run the example project, clone the repo, and run pod install from the Example directory first.

Requirements

  • iOS 8.0+ / macOS 10.9+ / tvOS 9.0+ / watchOS 2.0+
  • Xcode 9.1+
  • Swift 3.1+

Definition of the protocols

XMLBaseMappable Protocol

var nodeName: String! { get set }

This property is where the name of the XML node is being mapped

mutating func mapping(map: XMLMap)

This function is where all mapping definitions should go. When parsing XML, this function is executed after successful object creation. When generating XML, it is the only function that is called on the object.

Note: This protocol should not be implemented directly. XMLMappable or XMLStaticMappable should be used instead

XMLMappable Protocol (sub protocol of XMLBaseMappable)

init?(map: XMLMap)

This failable initializer is used by XMLMapper for object creation. It can be used by developers to validate XML prior to object serialization. Returning nil within the function will prevent the mapping from occuring. You can inspect the XML stored within the XMLMap object to do your validation:

required init?(map: XMLMap) {
    // check if a required "id" element exists within the XML.
    if map.XML["id"] == nil {
        return nil
    }
}

XMLStaticMappable Protocol (sub protocol of XMLBaseMappable)

XMLStaticMappable is an alternative to XMLMappable. It provides developers with a static function that is used by XMLMapper for object initialization instead of init?(map: XMLMap).

static func objectForMapping(map: XMLMap) -> XMLBaseMappable?

XMLMapper uses this function to get objects to use for mapping. Developers should return an instance of an object that conforms to XMLBaseMappable in this function. This function can also be used to:

  • validate XML prior to object serialization
  • provide an existing cached object to be used for mapping
  • return an object of another type (which also conforms to XMLBaseMappable) to be used for mapping. For instance, you may inspect the XML to infer the type of object that should be used for mapping

If you need to implement XMLMapper in an extension, you will need to adopt this protocol instead of XMLMappable.

How to use

To support mapping, a class or struct just needs to implement the XMLMappable protocol:

var nodeName: String! { get set }
init?(map: XMLMap)
mutating func mapping(map: XMLMap)

XMLMapper uses the <- operator to define how each property maps to and from XML:

<food>
  <name>Belgian Waffles</name>
  <price>5.95</price>
  <description>
    Two of our famous Belgian Waffles with plenty of real maple syrup
  </description>
  <calories>650</calories>
</food>
class Food: XMLMappable {
    var nodeName: String!

    var name: String!
    var price: Float!
    var description: String?
    var calories: Int?

    required init?(map: XMLMap) {}

    func mapping(map: XMLMap) {
        name <- map["name"]
        price <- map["price"]
        description <- map["description"]
        calories <- map["calories"]
    }
}

XMLMapper can map classes or structs composed of the following types:

  • Int
  • Bool
  • Double
  • Float
  • String
  • RawRepresentable (Enums)
  • Array<Any>
  • Dictionary<String, Any>
  • Object<T: XMLBaseMappable>
  • Array<T: XMLBaseMappable>
  • Set<T: XMLBaseMappable>
  • Dictionary<String, T: XMLBaseMappable>
  • Dictionary<String, Array<T: XMLBaseMappable>>
  • Optionals and Implicitly Unwrapped Optionals of all the above

Basic XML mapping

Convert easily an XML string to XMLMappable:

let food = Food(XMLString: xmlString)

Or an XMLMappable object to XML string:

let xmlString = food.toXMLString()

XMLMapper class can also provide the same functionality:

let food = XMLMapper<Food>().map(XMLString: xmlString)

let xmlString = XMLMapper().toXMLString(food)

Advanced mapping

Set nodeName property of your class to change the element's name:

food.nodeName = "myFood"
<myFood>
  <name>Belgian Waffles</name>
  <price>5.95</price>
  <description>
    Two of our famous Belgian Waffles with plenty of real maple syrup
  </description>
  <calories>650</calories>
</myFood>

Map easily XML attributes using the attributes property of the XMLMap:

<food name="Belgian Waffles">
</food>
func mapping(map: XMLMap) {
    name <- map.attributes["name"]
}

Map array of elements:

<breakfast_menu>
  <food>
    <name>Belgian Waffles</name>
    <price>5.95</price>
    <description>
      Two of our famous Belgian Waffles with plenty of real maple syrup
    </description>
    <calories>650</calories>
  </food>
  <food>
    <name>Strawberry Belgian Waffles</name>
    <price>7.95</price>
    <description>
      Light Belgian waffles covered with strawberries and whipped cream
    </description>
    <calories>900</calories>
  </food>
</breakfast_menu>
func mapping(map: XMLMap) {
    foods <- map["food"]
}

Create your own custom transform type by implementing the XMLTransformType protocol:

public protocol XMLTransformType {
    associatedtype Object
    associatedtype XML

    func transformFromXML(_ value: Any?) -> Object?
    func transformToXML(_ value: Object?) -> XML?
}

and use it in mapping:

func mapping(map: XMLMap) {
    startTime <- (map["starttime"], XMLDateTransform())
}

Map nested XML elements by separating names with a dot:

<food>
  <details>
    <price>5.95</price>
  </details>
</food>
func mapping(map: XMLMap) {
    price <- map["details.price"]
}

Note: Nested mapping is currently supported only:

  • for elements that are composed of only innerText (like the above example) and
  • for attributes

This means that in order to map the actual price of the food in the following XML:

<food>
  <details>
    <price currency="euro">5.95</price>
  </details>
</food>

You need to use an XMLMappable object instead of a Float:

class Price: XMLMappable {
    var nodeName: String!

    var currency: String!
    var actualPrice: Float!

    required init?(map: XMLMap) {}

    func mapping(map: XMLMap) {
        currency <- map.attributes["currency"]
        actualPrice <- map.innerText
    }
}

Because of currency attribute existence. The same applies to the following XML:

<food>
  <details>
    <price>
      5.95
      <currency>euro</currency>
  </details>
</food>

You need to use an XMLMappable object like:

class Price: XMLMappable {
    var nodeName: String!

    var currency: String!
    var actualPrice: Float!

    required init?(map: XMLMap) {}

    func mapping(map: XMLMap) {
        currency <- map["currency"]
        actualPrice <- map.innerText
    }
}

Because of currency element existence.


Swift 4.2 and unordered XML elements

Starting from Swift 4.2, XML elements are highly likely to have different order each time you run your app. (This happens because they are represented by a Dictionary)

For this, since version 1.5.2 of the XMLMapper you can map and change the order of the nodes that appear inside another node using nodesOrder property of XMLMap:

class TestOrderedNodes: XMLMappable {
    var nodeName: String!

    var id: String?
    var name: String?
    var nodesOrder: [String]?

    init() {}
    required init?(map: XMLMap) {}

    func mapping(map: XMLMap) {
        id <- map["id"]
        name <- map["name"]
        nodesOrder <- map.nodesOrder
    }
}

let testOrderedNodes = TestOrderedNodes()
testOrderedNodes.id = "1"
testOrderedNodes.name = "the name"
testOrderedNodes.nodesOrder = ["id", "name"]
print(testOrderedNodes.toXMLString() ?? "nil")

Note: If you want to change the ordering of the nodes, make sure that you include, in the nodesOrder array, all the node names that you want to appear in the XML string

Map CDATA wrapped values

Since version 2.0.0 of XMLMapper, CDATA support has added. CDATA wrapped strings now are mapped as an Array<Data> by default, instead of String which was the case in the previous versions. That had as a side effect the disability to serialize CDATA wrapped values.

For example using the following code:

class Food: XMLMappable {
    var nodeName: String!
    
    var description: String?
    
    init() {}
    
    required init?(map: XMLMap) {}
        
    func mapping(map: XMLMap) {
        description <- map["description"]
    }
}

let food = Food()
food.nodeName = "Food"
food.description = "Light Belgian waffles covered with strawberries & whipped cream"
print(food.toXMLString() ?? "nil")

Your result was always:

<Food>
    <description>
        Light Belgian waffles covered with strawberries &amp; whipped cream
    </description>
</Food>

In version 2.0.0 we introduce the build in XMLCDATATransform type, which can be used like this:

class Food: XMLMappable {
    var nodeName: String!
    
    var description: String?
    
    init() {}
    
    required init?(map: XMLMap) {}
        
    func mapping(map: XMLMap) {
        description <- (map["description"], XMLCDATATransform())
    }
}

let food = Food()
food.nodeName = "Food"
food.description = "Light Belgian waffles covered with strawberries & whipped cream"
print(food.toXMLString() ?? "nil")

and the result will be:

<Food>
    <description>
        <![CDATA[
            Light Belgian waffles covered with strawberries & whipped cream
        ]]>
    </description>
</Food>

The breaking change here is that the deserialization of CDATA wrapped values cannot achieved, unless you use XMLCDATATransform type. For example if you try to map the above XML to the following model class:

class Food: XMLMappable {
    var nodeName: String!
    
    var description: String?
    
    required init?(map: XMLMap) {}
        
    func mapping(map: XMLMap) {
        description <- map["description"]
    }
}

You will end up with nil as the value of description property.


Note: That default behaviour can be changed if you run xmlObject(withString:encoding:options:) function of XMLSerialization yourself and pass as options the default set, including cdataAsString option.

For example, the following code will work:

class Food: XMLMappable {
    var nodeName: String!
    
    var description: String?
    
    required init?(map: XMLMap) {}
        
    func mapping(map: XMLMap) {
        description <- map["description"]
    }
}

let xmlString = """
<Food>
    <description>
        <![CDATA[
            Light Belgian waffles covered with strawberries & whipped cream
        ]]>
    </description>
</Food>
"""
let data = Data(xmlString.utf8) // Data for deserialization (from XML to object)
do {
    let xml = try XMLSerialization.xmlObject(with: data, options: [.default, .cdataAsString])
    let food = XMLMapper<Food>().map(XMLObject: xml)
} catch {
    print(error)
}

XML Mapping example

map XML:

 <?xml version="1.0" encoding="UTF-8"?>
 <root>
    <TestElementXMLMappable testAttribute="enumValue">
        <testString>Test string</testString>
        <testList>
            <element>
                <testInt>1</testInt>
                <testDouble>1.0</testDouble>
            </element>
            <element>
                <testInt>2</testInt>
                <testDouble>2.0</testDouble>
            </element>
            <element>
                <testInt>3</testInt>
                <testDouble>3.0</testDouble>
            </element>
            <element>
                <testInt>4</testInt>
                <testDouble>4.0</testDouble>
            </element>
        </testList>
        <someTag>
            <someOtherTag>
                <nestedTag testNestedAttribute="nested attribute">
                </nestedTag>
            </someOtherTag>
        </someTag>
    </TestElementXMLMappable>
 </root>

to classes:

class TestXMLMappable: XMLMappable {
    var nodeName: String!

    var testElement: TestElementXMLMappable!
    var testNestedAttribute: String?

    required init?(map: XMLMap) {}

    func mapping(map: XMLMap) {
        testElement <- map["TestElementXMLMappable"]
        testNestedAttribute <- map.attributes["TestElementXMLMappable.someTag.someOtherTag.nestedTag.testNestedAttribute"]
    }
}

enum EnumTest: String {
    case theEnumValue = "enumValue"
}

class TestElementXMLMappable: XMLMappable {
    var nodeName: String!

    var testString: String?
    var testAttribute: EnumTest?
    var testList: [Element]?
    var nodesOrder: [String]?

    required init?(map: XMLMap) {}

    func mapping(map: XMLMap) {
        testString <- map["testString"]
        testAttribute <- map.attributes["testAttribute"]
        testList <- map["testList.element"]
        nodesOrder <- map.nodesOrder
    }
}

class Element: XMLMappable {
    var nodeName: String!

    var testInt: Int?
    var testDouble: Float?

    required init?(map: XMLMap) {}

    func mapping(map: XMLMap) {
        testInt <- map["testInt"]
        testDouble <- map["testDouble"]
    }
}

Requests subspec

Note: Requests subspec has different minimum deployment targets due to Alamofire dependency. (currently iOS 10.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+)

Create and send easily request with XML body using Alamofire (added missing XMLEncoding struct)

Alamofire.request(url, method: .post, parameters: xmlMappableObject.toXML(), encoding: XMLEncoding.default)

Also map XML responses to XMLMappable objects using the Alamofire extension. For example a URL returns the following CD catalog:

<CATALOG>
    <CD>
        <TITLE>Empire Burlesque</TITLE>
        <ARTIST>Bob Dylan</ARTIST>
        <COUNTRY>USA</COUNTRY>
        <COMPANY>Columbia</COMPANY>
        <PRICE>10.90</PRICE>
        <YEAR>1985</YEAR>
    </CD>
    <CD>
        <TITLE>Hide your heart</TITLE>
        <ARTIST>Bonnie Tyler</ARTIST>
        <COUNTRY>UK</COUNTRY>
        <COMPANY>CBS Records</COMPANY>
        <PRICE>9.90</PRICE>
        <YEAR>1988</YEAR>
    </CD>
</CATALOG>

Map the response as follows:

Alamofire.request(url).responseXMLObject { (response: DataResponse<CDCatalog>) in
    let catalog = response.result.value
    print(catalog?.cds?.first?.title ?? "nil")
}

The CDCatalog object will look something like this:

class CDCatalog: XMLMappable {
    var nodeName: String!

    var cds: [CD]?

    required init?(map: XMLMap) {}

    func mapping(map: XMLMap) {
        cds <- map["CD"]
    }
}

class CD: XMLMappable {
    var nodeName: String!

    var title: String!
    var artist: String?
    var country: String?
    var company: String?
    var price: Double?
    var year: Int?

    required init?(map: XMLMap) {}

    func mapping(map: XMLMap) {
        title <- map["TITLE"]
        artist <- map["ARTIST"]
        country <- map["COUNTRY"]
        company <- map["COMPANY"]
        price <- map["PRICE"]
        year <- map["YEAR"]
    }
}

Last but not least, create easily and send SOAP requests, again using Alamofire:

let soapMessage = SOAPMessage(soapAction: "ActionName", nameSpace: "ActionNameSpace")
let soapEnvelope = SOAPEnvelope(soapMessage: soapMessage)

Alamofire.request(url, method: .post, parameters: soapEnvelope.toXML(), encoding: XMLEncoding.soap(withAction: "ActionNameSpace#ActionName"))

The request will look something like this:

POST / HTTP/1.1
Host: <The url>
Content-Type: text/xml; charset="utf-8"
Connection: keep-alive
SOAPAction: ActionNameSpace#ActionName
Accept: */*
User-Agent: XMLMapper_Example/1.0 (org.cocoapods.demo.XMLMapper-Example; build:1; iOS 11.0.0) Alamofire/4.5.1
Accept-Language: en;q=1.0
Content-Length: 251
Accept-Encoding: gzip;q=1.0, compress;q=0.5

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
    <soap:Body>
        <m:ActionName xmlns:m="ActionNameSpace"/>
    </soap:Body>
</soap:Envelope>

Adding action parameters is as easy as subclassing the SOAPMessage class.

class MySOAPMessage: SOAPMessage {

    // Custom properties

    override func mapping(map: XMLMap) {
        super.mapping(map: map)

        // Map the custom properties
    }
}

Also specify the SOAP version that the endpoint use as follows:

let soapMessage = SOAPMessage(soapAction: "ActionName", nameSpace: "ActionNameSpace")
let soapEnvelope = SOAPEnvelope(soapMessage: soapMessage, soapVersion: .version1point2)

Alamofire.request(url, method: .post, parameters: soapEnvelope.toXML(), encoding: XMLEncoding.soap(withAction: "ActionNameSpace#ActionName", soapVersion: .version1point2))

and the request will change to this:

POST / HTTP/1.1
Host: <The url>
Content-Type: application/soap+xml;charset=UTF-8;action="ActionNameSpace#ActionName"
Connection: keep-alive
Accept: */*
User-Agent: XMLMapper_Example/1.0 (org.cocoapods.demo.XMLMapper-Example; build:1; iOS 11.0.0) Alamofire/4.5.1
Accept-Language: en;q=1.0
Content-Length: 248
Accept-Encoding: gzip;q=1.0, compress;q=0.5

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope/" soap:encodingStyle="http://www.w3.org/2003/05/soap-encoding">
    <soap:Body>
        <m:ActionName xmlns:m="ActionNameSpace"/>
    </soap:Body>
</soap:Envelope>

Unfortunately, there isn't an easy way to map SOAP response, other than creating your own XMLMappable objects (at least not for the moment)

Communication

  • If you need help, use Stack Overflow. (Tag 'xmlmapper')
  • If you'd like to ask a general question, use Stack Overflow.
  • If you found a bug, open an issue.
  • If you have a feature request, open an issue.

Installation

CocoaPods

XMLMapper is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'XMLMapper'

To install the Requests subspec add the following line to your Podfile:

pod 'XMLMapper/Requests'

Carthage

To integrate XMLMapper into your Xcode project using Carthage, add the following line to your Cartfile:

github "gcharita/XMLMapper" ~> 1.6

Swift Package Manager

To add XMLMapper to a Swift Package Manager based project, add the following:

.package(url: "https://github.com/gcharita/XMLMapper.git", from: "1.6.0")

to the dependencies value of your Package.swift.

Special thanks

License

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

Comments
  • Save XML data to UserDefaults

    Save XML data to UserDefaults

    Hello @gcharita , thanks for this great library. It is well appreciated.

    I will like to ask how best I can store data to my UserDefaults.

    I have already tried

    func saveListData(podList: [RSSFeeds]){
            let podData = NSKeyedArchiver.archivedData(withRootObject: podList)
            UserDefaults.standard.set(podData, forKey: "podData")
        }
    

    but i am getting the unrecognized selector sent to instance 0x600000c23040 error.

    Any insight to getting this resolved will be well appreciated.

    Regards,

    question 
    opened by meshileya 11
  • Alamofire 5.2 cannot convert value of type

    Alamofire 5.2 cannot convert value of type

    Hi GCharita,

    Since alamofire 5.2 i cannot convert DataResponse to expected type (DataResponse<T, AFError>).

    Please find attached the used code and a screenshot of the error. Can you help me throught with this issue?

    best regards,

    Patrick

    Alamofire 5.2 XMLMapper 2.0.0 Xcode 12.3

    Schermafbeelding 2020-12-29 om 15 59 23

    class AllCnannelModel : XMLMappable {
                
                var nodeName: String!
                
                var  id : Int?
                var  name: String?
                var  url : URL?
                var  picture : URL?
                var  category_id: Int?
    
                required init?(map: XMLMap) {}
    
                func mapping(map: XMLMap) {
                    id<-map["PERSONID"]
                    name<-map["NAME"]
                    url<-map["url"]
                    picture<-map["picture"]
                    category_id<-map["category_id"]
                }
            }
            
            let getallpersonsquery = GetAllPersonsQuery()
            getallpersonsquery.nodeName = "query"
            getallpersonsquery.sql = "SELECT personid, name FROM person where personid = 150"
            
            AF.request(RequestUrl, method: .post, parameters: getallpersonsquery.toXML(), encoding: XMLEncoding.default, headers: headers)
                .redirect(using: redirector)
                .responseXMLObject(completionHandler: (DataResponse<[AllCnannelModel], AFError>) -> Void) in
            }
    
        }
    
    question 
    opened by PatrickB100 9
  • Serialization for CDATA wrapped values

    Serialization for CDATA wrapped values

    CDATA deserialization works great out of the box. It would be great to create some approach to serialize CDATA wrapped values.

    For example:

    class MyData: XMLMappable {
        var nodeName: String!
        var cdataValue: String?
        ...
        func mapping(map: XMLMap) {
            cdataValue <- map.attributes["cdataValue"]
        }
    }
    
    let myData = MyData()
    myData.cdataValue = "actualValue"
    print(myData.toXMLString())
    
    <cdataValue><![CDATA[ actualValue ]]></cdataValue>
    
    enhancement discussion 
    opened by pazone 9
  • Recursive XML elements

    Recursive XML elements

    Hi!

    How would I go about handling recursive XML elements?

    E.g.

    <item>
      <id>1</id>
      <item>
        <id>2</id>
      </item>
    </item>
    
    question 
    opened by aaomidi 6
  • foobar2000 returns artist twice - once with just text, second time with attribute - XMLMapper can't access second array item

    foobar2000 returns artist twice - once with just text, second time with attribute - XMLMapper can't access second array item

    Good day, I found a problem when trying to connect to a foobar2000 server.

    The server returns:

    <upnp:artist>The 54 All-Stars</upnp:artist>
    <upnp:artist role="AlbumArtist">Various Artists</upnp:artist>
    

    And that's ok, because XMLMapper treats it like an array.

    However, I can't access the second item, no matter what I try.

    If I map it to a String, I just get the first item. Ok, that's fine, but the second item gets lost. So then I tried creating a new class:

    class SOAPItemAlbumArtist: XMLMappable {
    	required init?(map: XMLMap) {}
    	
    	var nodeName: String!
    
    	var artistName: String?
    	var artistRole: String?
    
    	func mapping(map: XMLMap) {
    		artistName <- map.innerText
    		artistRole <- map.attributes["role"]
    	}
    }
    

    And then the definition is as such:

    var artist: [SOAPItemAlbumArtist]?

    That causes a crash in XMLMapper.swift:90

    if var object = klass.init(map: map) as? N {

    I tried everything I could to figure this out, including tracing through the source code but I'm not familiar enough with it to determine exactly how to fix it, or if I'm just setting up my mapping incorrectly.

    Has anyone seen this issue? Is it a bug, or user error?

    need more info not reproducible 
    opened by mgainesdev 5
  • Cannot correctly parse elements with innerText and optional attributes

    Cannot correctly parse elements with innerText and optional attributes

    It is impossible to correctly parse elements that use innerText and optional attributes.

    Take the example in the README:

    <food>
      <details>
        <price currency="euro">5.95</price>
      </details>
    </food>
    
    class Price: XMLMappable {
        var nodeName: String!
    
        var currency: String!
        var actualPrice: Float!
    
        required init?(map: XMLMap) {}
    
        func mapping(map: XMLMap) {
            currency <- map.attributes["currency"]
            actualPrice <- map.innerText
        }
    }
    

    In this case, if the currency is optional so the input could include either <price currency="euro">5.95</price> or <price>5.95</price>, you cannot correctly parse the latter example. This is because the collapseTextNodes functionality in XMLObjectParser moves the 5.95 value to the parent dictionary if there are no attributes on the node. This leaves you with no reasonable way to parse both inputs with the same mapping object.

    opened by ewanmellor 5
  • Body is located before Header (Unordered tags)

    Body is located before Header (Unordered tags)

    Hello, I am trying to compose a SOAP request and have encountered a problem - for some reason in my request Body is located before Header and I don't understand how I can change it.

    This is how I create SOAPEnvelope where is information has header data and soapMessage has body data: let soapEnvelope = SOAPEnvelope(soapMessage: soapMessage, soapInformation: information, soapVersion: .version1point2)

    And for example when I try to print SOAPEnvelope (soapEnvelope.toXMLString()) I receive this string:

    <?xml version="1.0" encoding="utf-8"?> <soap:Envelope soap:encodingStyle="http://www.w3.org/2003/05/soap-encoding" xmlns:soap="http://www.w3.org/2003/05/soap-envelope"> <soap:Body> .... </soap:Body> <soap:Header> ... </soap:Header> </soap:Envelope>

    The problem is that I work with the ONVIF service and it is sensitive to the order of the header / body.

    Thanks

    bug 
    opened by Denis-Svichkarev 5
  • responseXMLObject Returns nil

    responseXMLObject Returns nil

    Hi I'm using your library to map SOAP responses. I'm trying to call a PING function, but it always returns me nil

    let soapMessage = SOAPMessage(soapAction: "Ping", nameSpace: actionNameSpace)
    let soapEnvelope = SOAPEnvelope(soapMessage: soapMessage, soapVersion: .version1point2)
    
    Alamofire.request(Url, method: .post, parameters: soapEnvelope.toXML(), encoding: XMLEncoding.soap(withAction: "\(actionNameSpace)#PingResponse", soapVersion: .version1point2)).responseXMLObject { (response: DataResponse<PingResponse>) in
                print(response.result.value?.PingResult) 
            }
    

    This is the request (tested with SoapUI)

    <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:tem="http://tempuri.org/">
       <soap:Header/>
       <soap:Body>
          <tem:Ping/>
       </soap:Body>
    </soap:Envelope>
    

    This is the response

    <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
      <soap:Body>
        <PingResponse xmlns="http://tempuri.org/">
          <PingResult>true</PingResult>
        </PingResponse>
      </soap:Body>
    </soap:Envelope>
    

    Can you help me?

    question 
    opened by SalvatoreAD 5
  • Ordered XML Attributes

    Ordered XML Attributes

    When I write to XML string, I want to be in order attributes. How do I do this?

    example:

    class TestOrderedAttributes: XMLMappable {
       var NodeName: String!
       var attribute1: String?
       var attribute2: String?
       var attribute3: String?
    
       init() {}
       required init?(map:XMLMap) {}
    
       func mapping(map: XMLMap) {
          attribute1 <- map.attributes["attribute1"]
          attribute2 <- map.attributes["attribute2"]
          attribute3 <- map.attributes["attribute3"]
       }
    }
    
    let testOrderedAttributes = TestOrderedAttributes()
    testOrderedAttributes.attribute1 = "1"
    testOrderedAttributes.attribute2= "2"
    testOrderedAttributes.attribute3 = "3"
    testOrderedAttributes.attributesOrder = ["attribute3", "attribute2", "attribute1"]
    
    
    invalid discussion feature request 
    opened by jinsit 3
  • crashes most of times

    crashes most of times

    Hi guys,

    Almost of times the app crash with random xmls on this line. func addText(_ additionalText: String) { if case nil = text?.append(additionalText) { text = additionalText } }

    It throws this exception on console: (17940,0x70000e800000) malloc: *** error for object 0x600000862ac0: Non-aligned pointer being freed (2) *** set a breakpoint in malloc_error_break to debug

    Could you help me? :)

    need more info 
    opened by agenterouser 3
  • Question regarding dots in value

    Question regarding dots in value

    Hi Gcharita,

    • I'm having the following issue, a have a mapping where i have a dot in between a single value. Is this a bug or not? if so, is there a workaround?

    This code is not working, there is a dot in the middle of LINE.NAME

    func mapping(map: XMLMap) {
                lineName <- map["LINE.NAME"]
    

    This code is fully working. There is no dot in the middle of LINENAME

    func mapping(map: XMLMap) {
                lineName <- map["LINENAME"]
    

    thanks in advance,

    Patrick

    question 
    opened by PatrickB100 2
  • How can I use Requests classes with Swift Package Manager?

    How can I use Requests classes with Swift Package Manager?

    Hi,

    I’m trying to use the XMLEncoding that is part of the Request target but I'm seeing that it is excluded in Package.swift I know I can achieve this with CocoaPods but is it possible to achieve the same with SPM?

    Thanks in advance.

    opened by drmendozaz 1
Releases(2.0.0)
  • 2.0.0(Dec 21, 2020)

  • 1.6.1(Apr 13, 2020)

  • 1.6.0(Dec 24, 2019)

  • 1.5.3(May 24, 2019)

  • 1.5.2(Jan 4, 2019)

    • Closed #15. Removed stripEmptyNodes from default ReadingOptions of XMLSerialization
    • Fixed #18. Added nodesOrder property in XMLMap to preserve or change the nodes ordering
    • Fixed nested mapping for attributes in XMLMap
    Source code(tar.gz)
    Source code(zip)
  • 1.5.1(Jul 23, 2018)

  • 1.5.0(Jun 20, 2018)

    • Added support for Swift 4.2 and Xcode 10. Fixed invalid redeclaration errors. (warnings will remain in Swift 4.1 compiler, due to the fact that IUO do not behave the same way as in Swift 4.2 compiler)
    • Fixed flatMap deprecation warnings.
    • Fixed support for Swift 3.0 and Xcode 8.3.
    • Fixed XMLSerialization to support XMLs with XML declaration
    • Improved XMLMapper to support mapping of dictionary of XMLMappable and dictionary of arrays of XMLMappable objects.
    • XMLSerialization can now return array of dictionaries
    • Added support to map enums with rawValue of LosslessStringConvertible.
    • Added support to map array of Any with single element.
    • Added tests that cover more than half of the project.
    Source code(tar.gz)
    Source code(zip)
  • 1.4.4(Apr 1, 2018)

  • 1.4.3(Feb 16, 2018)

  • 1.4.2(Feb 4, 2018)

    • Fixed changes that broke Swift 3.1 and Xcode 8.3 support
    • Added innerText property in XMLMap to map directly the text of current XML node #1
    • General code improvements
    Source code(tar.gz)
    Source code(zip)
  • 1.4.1(Jan 25, 2018)

  • 1.4.0(Jan 4, 2018)

  • 1.3.0(Nov 5, 2017)

    • Removed XMLDictionary dependency and replaced with Swift code
    • Added ReadingOptions in XMLSerialization
    • Added documentation in XMLSerialization
    • Minor code improvements
    Source code(tar.gz)
    Source code(zip)
  • 1.2.0(Oct 12, 2017)

    • Added Requests subspec for making xml requests with Alamofire
    • Added classes for making SOAP request (supports SOAP v1.1 and v1.2)
    • Minor code improvements
    Source code(tar.gz)
    Source code(zip)
  • 1.0.0(Oct 3, 2017)

  • 0.1.0(Sep 27, 2017)

Owner
Giorgos Charitakis
Giorgos Charitakis
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
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
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
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
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
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
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
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
📄 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

Abdullah Aljahdali 14 Dec 31, 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
Mathias Köhnke 1.1k Dec 16, 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
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
Demo in SwiftUI of Apple Map, Google Map, and Mapbox map

SNMapServices SNMapServices is a serices for iOS written in SwiftUI. It provides Map capability by subclassing Mapbox, Google map and Apple map. This

Softnoesis 3 Dec 16, 2022
An exercise to use a map(google map) for navigation.

map-navigation An exercise to use a map(google map) for navigation. It have the features of navigating your for a destination, drawing your travel pat

HongXing Liao 2 Dec 16, 2022
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

Edwin Vermeer 65 Dec 29, 2020
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