这是我的第一个iOS应用程序,我在从XML获取数据方面遇到了一些麻烦。我需要从XML文件中获取歌曲名称和艺术家,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<Schedule System="Jazler">
<Event status="happening" startTime="19:14:30" eventType="song">
<Announcement Display="Now On Air:"/>
<Song title="E timpul">
<Artist name="Revers">
</Artist>
<Jazler ID="16490"/>
<PlayLister ID=""/>
<Media runTime="03:03"/>
<Expire Time="19:17:33"/>
</Song>
</Event>
</Schedule>
到目前为止,我认为我创建了解析器,但我不知道如何从中获取数据,在线教程让我感到困惑......
self.parser = XMLParser(contentsOf: URL(string:"http://localhost/jazler/NowOnAir.xml")!)!
self.parser.delegate = self as? XMLParserDelegate
let success:Bool = self.parser.parse()
if success {
print("success")
} else {
print("parse failure!")
}
非常感谢您的帮助。提前谢谢。
答案 0 :(得分:2)
由于您的XML包含具有元素属性的所有值,因此您不需要实现foundCharacters
。只需didStartElement
,例如,您的解析器委托可能看起来很简单:
var song: String?
var artist: String?
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
switch elementName {
case "Song": song = attributeDict["title"]
case "Artist": artist = attributeDict["name"]
default: break
}
}
两个观察结果:
我倾向于将此解析代码从视图控制器中拉出来,并将其放在专用对象中,以帮助防止&#34;查看控制器膨胀&#34;。
如果对请求的响应有点慢,我也会使用URLSession
。通常,应该避免使用XMLParser(contentsOf:)
,因为它会同步执行请求。
在您的情况下,由于您要求来自localhost
的数据,或许这不是一个问题。但是,仍然谨慎地始终异步执行HTTP请求。
无论如何,这可能会产生类似的结果:
class SongParser: NSObject {
var song: String?
var artist: String?
class func requestSong(completionHandler: @escaping (String?, String?, Error?) -> Void) {
let url = URL(string: "http://localhost/jazler/NowOnAir.xml")!
let task = URLSession.shared.dataTask(with: url) { data, _, error in
guard let data = data, error == nil else {
DispatchQueue.main.async {
completionHandler(nil, nil, error)
}
return
}
let delegate = SongParser()
let parser = XMLParser(data: data)
parser.delegate = delegate
DispatchQueue.main.async {
completionHandler(delegate.song, delegate.artist, parser.parserError)
}
}
task.resume()
}
}
extension SongParser: XMLParserDelegate {
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
switch elementName {
case "Song": song = attributeDict["title"]
case "Artist": artist = attributeDict["name"]
default: break
}
}
}
你可以像这样使用它:
SongParser.requestSong { song, artist, error in
guard let song = song, let artist = artist, error == nil else {
print(error ?? "Unknown error")
return
}
print("Song:", song)
print("Artist:", artist)
}
答案 1 :(得分:1)
首先将xml转换为NSData并调用解析器来解析它。
//converting into NSData
var data: Data? = theXML.data(using: .utf8)
//initiate NSXMLParser with this data
var parser: XMLParser? = XMLParser(data: data ?? Data())
//setting delegate
parser?.delegate = self
//call the method to parse
var result: Bool? = parser?.parse()
parser?.shouldResolveExternalEntities = true
现在,您需要在您的类中实现NSXMLParser委托。
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
currentElement = elementName
print("CurrentElementl: [\(elementName)]")
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
print("foundCharacters: [\(string)]")
}
您将在xml的密钥下找到该值。