简体   繁体   English

如何在Swift中使用XML字符串初始化NSXMLDocument?

[英]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. 我正在尝试从xml字符串获取值,但是对于Swift来说,我是不知道如何初始化NSXMLDocument对象的。 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". 我收到错误消息“无法为接受提供的参数的'init'找到重载”。 I've tried converting the string to NSData but I end up with the same error: 我尝试将字符串转换为NSData,但最终遇到相同的错误:

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. NSXMLDocument不包含初始化程序,而仅将字符串作为参数。 There is initWithXMLString:options:error: though, which should solve your problem. 不过有initWithXMLString:options:error:可以解决您的问题。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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