I am trying to do XML Parsing of below file :
<bgmusic>
<genre title=“Title1”>
<track title=“SubTitle1” path="https://test/Background_Track%20-%20Ambient%20-%20ANW2856_01_ Animation.ogg" />
<track title="SubTitle2” path="https://test/Background_Track%20-%20Ambient%20-%20ANW2860_02_Entanglement.ogg" />
</genre>
<genre title="Title2”>
<track title="SubTitle3” path="https://test/Background_Track%20-%20Ambient%20-%20ANW2856_01_Animate.ogg" />
<track title="SubTitle4” path="https://test/Background_Track%20-%20Ambient%20-%20ANW2860_02_ SubTitle4.ogg" />
</genre>
</bgmusic>
Basically I have created two ViewController, one for displaying Genre Title and second VC for displaying the details of this. For this, I have created below two Modal classes:
class GenreModel {
var title: String = ""
var genreSongsArray = [GenreSong]()
var genreSongs = GenreSong()
}
class GenreSong {
var songTitle: String = ""
var path: String = ""
}
Here is my code:
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
let genreModel = GenreModel()
if(elementName == "genre"){
if let id = attributeDict["title"] {
genreModel.title = id
}
}
if(elementName == "track")
{
let genreSong = GenreSong()
for string in attributeDict {
let strvalue = string.value as NSString
switch string.key {
case "title":
genreSong.songTitle = strvalue as String
break
case "path":
genreSong.path = strvalue as String
break
default:
break
}
}
genreModel.genreSongsArray.append(genreSong)
}
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
}
My problem is when I am giving "elementName == genre" then it's only parsing genre title and not parsing track details. How can I save both Genre title and Songs details in one custom Array?
Can anyone please suggest me on this? Thank you!
XMLParserDelegate? You need to keep the results (see yourlet genreModel = GenreModel(), it's a local variable and can never accessed again one the methods is finished) inside the class.