我想将 XML 字符串转换为元组。
var responseXml =
"""
<?xml version="1.0"?>
<tmweb>
<booking type='come' time='71102' persnr='9999' name='Test' firstname='Max' title='Mr.'/>
</tmweb>
"""
responseXml.removeFirst(39) // Remove the beginning of the XML
responseXml.removeLast(11) // Remove the end of the XML
responseXml = responseXml.replacingOccurrences(of:" ", with: ";") // Replace empty place with ;
responseXml = responseXml.replacingOccurrences(of: "'", with: "\"") // Replace ' to "
responseXml = responseXml.replacingOccurrences(of: "=", with: ": ") // Replace = to :(space)
临时输出:
"type: "come";time: "71102";persnr: "9999";name: "Test";firstname: "Max";title: "Mr."\n"
目前我只有整个字符串作为 UIAlert 的替换
我的下一步:
我想将秒 (71102) 转换为可读的时间格式,例如 19:45:22
func secs2time (_ seconds : Int) -> (Int,Int,Int) {
return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}
目前很难找到好的解决方案。
有什么建议吗?
最佳答案
要处理xml
,您需要使用NSXMLParser
。这里有两个网站可以为您提供帮助。
http://leaks.wanari.com/2016/08/24/xml-parsing-swift/ https://medium.com/@lucascerro/understanding-nsxmlparser-in-swift-xcode-6-3-1-7c96ff6c65bc
这是一个小例子:
var url = NSURL(string: "http://example.com/website-with-xml")
var xmlParser = NSXMLParser(contentsOfURL: url)
xmlParser.delegate = self
xmlParser.parse()
func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!, attributes attributeDict: NSDictionary!) {
println("Element's name is \(elementName)")
println("Element's attributes are \(attributeDict)")
}
时间转换可以在其他问题here中找到在计算器中:
Define
func secondsToHoursMinutesSeconds (seconds : Int) -> (Int, Int, Int) {
return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}
Use
secondsToHoursMinutesSeconds(27005) (7,30,5)
or
let (h,m,s) = secondsToHoursMinutesSeconds(27005)
The above function makes use of Swift tuples to return three values at once. You destructure the tuple using the
let (var, ...)
syntax or can access individual tuple members, if need be.If you actually need to print it out with the words
Hours
etc then use something like this:
func printSecondsToHoursMinutesSeconds (seconds:Int) -> () {
let (h, m, s) = secondsToHoursMinutesSeconds (seconds)
print ("\(h) Hours, \(m) Minutes, \(s) Seconds")
}
Note that the above implementation of
secondsToHoursMinutesSeconds()
works forInt
arguments. If you want aDouble
version you'll need to decide what the return values are - could be(Int, Int, Double)
or could be(Double, Double, Double)
. You could try something like:
func secondsToHoursMinutesSeconds (seconds : Double) -> (Double, Double, Double) {
let (hr, minf) = modf (seconds / 3600)
let (min, secf) = modf (60 * minf)
return (hr, min, 60 * secf)
}
关于ios - 如何将 xml 字符串分成元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48649191/