4

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.

David Mohundro
  • 11,922
  • 5
  • 40
  • 44
Zinathene
  • 41
  • 1
  • 3

1 Answers1

5

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.

David Mohundro
  • 11,922
  • 5
  • 40
  • 44
  • Could you please have a look at my issue that I'm having with SWXMLHash. http://stackoverflow.com/questions/35236190/how-to-use-more-efficiently-swxmlhash-and-how-to-set-the-class-that-will-receive?noredirect=1#comment58257438_35236190 – AziCode Feb 17 '16 at 01:09