Home > Software design >  Swift Xcode XML string to String of Array
Swift Xcode XML string to String of Array

Time:11-27

sorry can't get it to work.

I have an xml string:

<data>
   <project>123 first</project>
   <project>234 second</project>
   <project>345 third</project>
</data>

I now use a function where I look for project in the string and then find the correct value and append it to my StringArray

var StringArray: [String] = []

this works as expected but now the project is growing to over 2000 records in the xml file and it takes more than 15 seconds to get the values in the StringArray.

public func getArrayFromXMLString(xml: String, node: String) -> [String] {
    var xml2: String = xml
    var ArrayName = [String]()
    while xml2.range(of: "<"   node   ">") != nil {
        let i1 : Int = xml2.indexOf("<"   node   ">")!
        xml2 = xml2.right(xml2.length - i1)
        let i2 : Int = xml2.indexOf(">")!
        xml2 = xml2.right(xml2.length - i2 - 1)
        let i3 : Int = xml2.indexOf("<")!
        ArrayName.append(xml2.left(i3))
    }
    return ArrayName
}

(some functions are used for indexof, left and right)

I found a lot of examples with XMLParser but none with only the one property. I have obviously never used XMLParser.

Can someone guide me in the correct way please?

CodePudding user response:

It's not so complicated to use the XMLParser class, specially with this simple structure.

For the delegate we implement 3 of the protocol methods, two to keep track of if the currently parsed object is a project element and one to read the value.

class ParserDelegate: NSObject, XMLParserDelegate {
    var projects = [String]()
    var isProject = false

    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
        if !isProject, elementName == "project" { isProject = true }
    }

    func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
        isProject = false
    }

    func parser(_ parser: XMLParser, foundCharacters string: String) {
        if isProject { projects.append(string)}
    }
}

Example

let parser = XMLParser(data: data)
let delegate = ParserDelegate()
parser.delegate = delegate
parser.parse()
print(delegate.projects)

["123 first", "234 second", "345 third"]

  • Related