Alec.
Alec.

Reputation: 5525

Swift - Get XML attrributes

I am trying to loop through the following example XML using CheatyXML

<subsonic-response xmlns="http://subsonic.org/restapi" status="ok" version="1.16.0">
<indexes lastModified="1524417436798" ignoredArticles="The El La Los Las Le Les">
<index name="E">
<artist id="14" name="Editors"/>
</index>
<index name="K">
<artist id="27" name="Kings Of Leon"/>
</index>
</indexes>
</subsonic-response>

I have an artist object that contains the artist name and artist ID. My goal is to populate an array of Artists with the relevent information.

I am struggling to loop through the XML correctly though, the code below returns the same artist (Editors) twice. Please help.

func getArtists()->[Artist]{
    var artist = [Artist]()
    //GET SAVED SUBIFY INFORMATION
    let defaults = UserDefaults.standard
    let server:String = defaults.string(forKey: "Server")!
    let username:String = defaults.string(forKey: "Username")!
    let password:String = defaults.string(forKey: "Password")!

    //PARSE XML TO GET VALUE
    let url = URL(string:"\(server)/rest/getIndexes?u=\(username)&p=\(password)&v=1.12.0&c=Subify")
    let parser:CXMLParser! = CXMLParser(contentsOfURL:url!)
    for element in parser["indexes"] {
        var artistAdd = Artist()
        artistAdd.id = parser["indexes"]["index"]["artist"].attribute("id").string!
        artistAdd.name = parser["indexes"]["index"]["artist"].attribute("name").string!
        dump(artistAdd)

    }
    //RETURN VALUE
    dump(artist)
    return artist

}

This is the library I'm using https://github.com/lobodart/CheatyXML

Upvotes: 0

Views: 70

Answers (1)

IMSoP
IMSoP

Reputation: 97688

In your for loop, you define element as the variable that contains the current element on each iteration:

for element in parser["indexes"] {

...but then inside the loop, you don't use element, you go back to the root of the document, so the library has no way of knowing which element you want, and defaults to giving you the first one:

artistAdd.id = parser["indexes"]["index"]["artist"].attribute("id").string!

I think all you need to do is actually use your loop variable in the loop:

artistAdd.id = element["artist"].attribute("id").string!

Upvotes: 1

Related Questions