iosswiftxmlxcodexmlmapper

swift parsing xml response odoo


I'm searching a framework to parse xml to a swift class on swift

i have response like that

<?xml version='1.0'?>
<methodResponse>
    <params>
        <param>
            <value>
                <array>
                    <data>
                        <value>
                            <struct>
                                <member>
                                    <name>id</name>
                                    <value>
                                        <int>23</int>
                                    </value>
                                </member>
                                <member>
                                    <name>name</name>
                                    <value>
                                        <string>20190111_Patient _Test 1_Frank</string>
                                    </value>
                                </member>
                                <member>
                                    <name>partner_id</name>
                                    <value>
                                        <boolean>0</boolean>
                                    </value>
                                </member>
                            </struct>
                        </value>
                    </data>
                </array>
            </value>
        </param>
    </params>
</methodResponse>

To parse it i'm trying to use XMLMapper from https://github.com/gcharita/XMLMapper

parsing is convert from this response to an object

the problem is that response of xml has no name on the nodes how can i parse correctly this thing ? any help would be appreciated


Solution

  • You can use XMLMapper nested mapping with the following model:

    class MethodResponse: XMLMappable {
        var nodeName: String!
    
        var members: [Member]?
    
        required init?(map: XMLMap) {}
    
        func mapping(map: XMLMap) {
            members <- map["params.param.value.array.data.value.struct.member"]
        }
    }
    
    class Member: XMLMappable {
        var nodeName: String!
    
        var name: String?
        var value: Value?
    
        required init?(map: XMLMap) {}
    
        func mapping(map: XMLMap) {
            name <- map["name"]
            value <- map["value"]
        }
    }
    
    class Value: XMLMappable {
        var nodeName: String!
    
        var string: String?
        var int: Int?
        var boolean: Int?
    
        required init?(map: XMLMap) {}
    
        func mapping(map: XMLMap) {
            string <- map["string"]
            int <- map["int"]
            boolean <- map["boolean"]
        }
    }
    

    and map your XML calling init(XMLString:) function of MethodResponse class like:

    let methodResponse = MethodResponse(XMLString: xmlString)
    

    Hope this helps.