how to use more efficiently SWXMLHash and how to set the class that will receive the data properly?

前端 未结 1 1764
心在旅途
心在旅途 2021-01-17 00:56

I\'m building a project for a train schedule app, and I\'m using an API that returns an XML file,to manipulate the data i\'m using the library called SWXMLHash.

I ne

相关标签:
1条回答
  • 2021-01-17 01:35

    I used the below code in the SWXMLHash playground and it works on my machine:

    // you need to model the ETD element as that has the destination and etd elements
    class Etd {
        var destination: String = ""
        var estimates = [String]()
    
        init(destination: String, estimates: [String]) {
            self.destination = destination
            self.estimates = estimates
        }
    }
    
    // each station has a collection of ETDs (per the XML)
    class Station {
        var name : String
        var etds = [Etd]()
    
        init(withName name: String, etds: [XMLIndexer]){
            self.name = name
    
            for etd in etds {
                self.etds.append(Etd(
                    destination: etd["destination"].element!.text!,
                    estimates: etd["estimate"].all.map { $0["minutes"].element!.text! })
                )
            }
        }
    }
    
    var stationsTest = [Station]()
    
    for elem in xml["root"]["station"] {
        var stations = elem["name"].element!.text!
        var stationPlaceHolder = Station(withName: stations, etds: elem["etd"].all)
        stationsTest.append(stationPlaceHolder)
    }
    

    Basically, it looks like what you were missing was the abstraction for the Etd class - a station doesn't contain a list of destinations, but a list of Etds. Each Etd then has both a destination and estimates by minute.

    0 讨论(0)
提交回复
热议问题