Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can I map the first word or a specific portion of a xml? #12

Closed
jeremiasdsa opened this issue Apr 30, 2018 · 1 comment
Closed

How can I map the first word or a specific portion of a xml? #12

jeremiasdsa opened this issue Apr 30, 2018 · 1 comment
Labels

Comments

@jeremiasdsa
Copy link

Hi @gcharita,

Is that possible to parse just the first word or the portion I want from the xml?
ex:
In this case I need just the first word, "Belgian" from food.

<Response> <food>Belgian Waffles</food> </Response>

@gcharita
Copy link
Owner

gcharita commented May 1, 2018

You can pretty much do whatever you like in the mapping process by implementing your own custom XMLTransformType.

To map the first word of the food element's value, your can use:

class FirstWordTransform: XMLTransformType {
    typealias Object = String
    typealias XML = String
    
    func transformFromXML(_ value: Any?) -> Object? {
        if let stringValue = value as? String {
            return stringValue.components(separatedBy: " ").first
        }
        return nil
    }
    
    func transformToXML(_ value: Object?) -> XML? {
        // If you don't want το discard the rest of the string value in the serialization process,
        // you can probably keep it in a variable inside this XMLTransformType's instance AND
        // keep this XMLTransformType's instance inside Reponse class instance.
        // (although this will not be so pretty)
        return value
    }
}

class Response: XMLMappable {
    var nodeName: String!
    
    var foodFirstWord: String?
    
    required init(map: XMLMap) {
        
    }
    
    func mapping(map: XMLMap) {
        foodFirstWord <- (map["food"], FirstWordTransform())
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants