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

Problem parsing XML with single or multiple elements #3

Closed
sewalsh opened this issue Feb 27, 2018 · 2 comments
Closed

Problem parsing XML with single or multiple elements #3

sewalsh opened this issue Feb 27, 2018 · 2 comments
Assignees

Comments

@sewalsh
Copy link

sewalsh commented Feb 27, 2018

Take the following for example:

<foo>
    <bar>
         <item></item>
   <bar>
   <bar>
         <item></item>
         <item></item>
   </bar>
</foo>

You have to make a choice to either parse as a single item or an array [item]. Both options are not available.

@gcharita gcharita self-assigned this Feb 28, 2018
@gcharita
Copy link
Owner

This is an interesting issue. I might have an idea on how to solve it.

Until the next release you can map the following example XML:

<foo>
    <bar>
        <item>1</item>
    </bar>
    <bar>
        <item>2</item>
        <item>3</item>
    </bar>
</foo>

Using this trick:

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

class Bar: XMLMappable {
    var nodeName: String!
    
    var items: [Int]?
    private var item: Int?
    
    required init(map: XMLMap) {
        
    }
    
    func mapping(map: XMLMap) {
        items <- map["item"]
        item <- map["item"]
        if let singleItem = item {
            items = [singleItem]
        }
    }
}

It isn't pretty but will do the job.

@sewalsh
Copy link
Author

sewalsh commented Feb 28, 2018

Cheers! This worked.

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

No branches or pull requests

2 participants