TERACytE TERACytE - 1 year ago 76
Swift Question

How do you initialize NSXMLDocument with an XML string in Swift?

I'm trying to acquire values from an xml string, but being new to Swift I can't figure out how to initialize the NSXMLDocument object. I'm trying:

var xmlString:String = "<?xml version=\"1.0\"><results><item1><name>Something</name><price>10.99</price></item1></results>"
var xml:NSXMLDocument = NSXMLDocument(xmlString)

I'm getting the error "Cannot find an overload for 'init' that accepts the supplied arguments". I've tried converting the string to NSData but I end up with the same error:

var nsData:NSData = xmlString.dataUsingEncoding(NSUTF8StringEncoding)
var xml:NSXMLDocument = NSXMLDocument(nsData)

Answer Source

NSXMLDocument doesn't contain an initializer than only takes a string as a parameter. There is initWithXMLString:options:error: though, which should solve your problem. Something like:

let xmlString = "<?xml version=\"1.0\"><results><item1><name>Something</name><price>10.99</price></item1></results>"
var error: NSError?
let xml = NSXMLDocument(XMLString: xmlString, options: 0, error: &error)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download