简体   繁体   中英

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM