Search code examples
iosxmlswiftnsxmlparser

Variable not accessible outside of function Swift


Here is the problem i am trying to parse XML in Swift everything works except for values.

import UIKit


class ItemParser: NSObject, XMLParserDelegate {
var parser = XMLParser()
var element:String!
var currentName:String = String()


func beginParsing()
{
    parser = XMLParser(contentsOf:(NSURL(string:"URL"))! as URL)!
    parser.delegate = self
    parser.parse()
}

func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String])
{
    element = elementName
}

func parser(_ parser: XMLParser, foundCharacters string: String)
{
    if element.isEqual("name") {
        currentName = string
    }
    print (currentName) -- displaying correctly
}

func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?)
{
    if elementName.isEqual("inv") {

        print("begginging")
        print(currentName) -- displaying nothing

}
}

To my Understanding i have declared all variable in the correct place but the variable is not retaining outside of function. What am i doing wrong?


Solution

  • Since the character value for an XML element can be huge it is possible that foundCharacters is called multiple times for the same element. So you have to append the characters to your class variable until didEndElement is being called for that element:

    func parser(_ parser: XMLParser, foundCharacters string: String)
    {
        if element.isEqual("name") {
            currentName += string  // append here
        }
    }
    

    And you have to take care on correctly resetting this variable on a new element:

    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String])
    {
        element = elementName
        currentName = ""  // reset 
    }
    
    func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?)
    {
        if elementName.isEqual("inv") {
    
            print("begginging")
            print(currentName) // is now complete
        }
    }