已编辑代码2,现在它更具功能:这是我要解析的通用xml文件,我需要在publicID属性中获取描述文字和URL:
<xml>
<event publicID="smi:www.website.net/...">
<type> </type>
<description>
<type> </type>
<text> </text>
</description>
</event>
<event publicID="smi:www.website2.net/...">
<type> </type>
<description>
<type> </type>
<text> </text>
</description>
</event>
...
这是我的代码,根据XMLParserDelegate:
Import UIKit
struct Event{
var urlEventi: String
}
struct Description {
var descrizioneTesto: String
}
var publicIDS: [Event] = []
var descrizioni: [Description] = []
var element: String = String()
var elementoPublicID: String = String()
var elementoDescription: String = String()
var eventPublicID = String()
var descriptionText = String()
在FirstViewController中,使用parser.parse()和:
// 1
func parser(_ parser: XMLParser, didStartElement elemento: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
if elementoPublicID == "event" {
eventPublicID = attributeDict["publicID"] ?? "NIL"
}
if elementoDescription == "description" {
descriptionText = String()
}
elementoPublicID = elemento
elementoDescription = elemento
}
// 2
func parser(_ parser: XMLParser, didEndElement elemento: String, namespaceURI: String?, qualifiedName qName: String?) {
let urlEventoGenerico = Event(urlEventi: eventPublicID)
let EventoGenerico = Description(descrizioneTesto: descriptionText)
if elemento == "event" {
publicIDS.append(urlEventoGenerico)
print("PublicID:",urlEventoGenerico.urlEventi)
}
if elemento == "description" {
descrizioni.append(EventoGenerico)
print("DescriptionText:", EventoGenerico.descrizioneTesto)
}
}
// 3
func parser(_ parser: XMLParser, foundCharacters string: String) {
let data = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
if (!data.isEmpty) {
if elementoPublicID == "event" {
eventPublicID += data
}
if elementoDescription == "text" {
descriptionText += data
}
}
}
好吧,解析非常适合描述文本,而URL列表是NIL的序列(如果我在解析过程中未在didStartElement中添加??“ NIL”,则会出现obv “致命错误:展开一个可选值时意外发现nil“ )...那么,错误在哪里?谢谢!
PARSING RESULT:
PublicID: NIL
DescriptionText: perfect
PublicID: NIL
DescriptionText: perfect
PublicID: NIL
DescriptionText: perfect
...