简体   繁体   中英

Iterating Through an XML file using SWXMLHash for Swift

Here is my Code block for this,

var a = 0;

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
    data, response, error in

    if error != nil {
        println("error=\(error)")
        return
    }

    responseString = NSString(data: data, encoding: NSUTF8StringEncoding)!

    let xmlWithNamespace = responseString
    var xml = SWXMLHash.parse(xmlWithNamespace)

    var entity = xml["row"]["ftc"]["Entity"][a]

    if entity.element?.attributes["ID"] != nil {

        entity = xml["row"]["ftc"]["Entity"][a]
        //println(a)

        println(entity.element?.attributes["ID"])
        a++
    } else {
        println("Print We Have Reached Our Limit")
    }

}
task.resume()

I am trying to get an iterator to go through and print out all the children and attributes of these inside and store them in a variable.

I have been looking everywhere for some help but Swift and XML are just a headache - any help to get me to iterate through the node would be amazing, I tried to use a while loop but it just crashed the program after giving me the nodes.

I am trying to use this while loop but even that won't work,

while entity.element?.attributes["ID"] != nil {
    entity = xml["row"]["ftc"]["Entity"][a]
    //println(a)

    println(entity.element?.attributes["ID"])
    a++
    break
}

Help would be appreciated it.

I realize this answer comes a few months later, but you may have been using an old version of SWXMLHash when this question was posted. I added a new method to SWXMLHash called children which lets you enumerate child elements. Given that, you can then use recursion to iterate over all of the elements.

Here is a code snippet that might help:

let xml = SWXMLHash.parse(xmlWithNamespace)

func enumerate(indexer: XMLIndexer, level: Int) {
    for child in indexer.children {
        var name = child.element!.name
        println("\(level) \(name)")

        enumerate(child, level + 1)
    }
}

enumerate(xml, 0)

You would also be able to grab the attributes off of each element this way, too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM