РЕДАКТИРОВАННЫЙ код 2, теперь он более функциональный: Это мой общий xml-файл для анализа, мне нужно получить текст описания и URL в атрибуте publicID:
<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, viewDidLoad с 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 (если я не добавляю ?? «NIL» в didStartElement во время синтаксического анализа, я получаю obv «Неустранимая ошибка: неожиданно обнаружен nil при развертывании необязательного значения» )... так где же ошибка?Спасибо!
PARSING RESULT:
PublicID: NIL
DescriptionText: perfect
PublicID: NIL
DescriptionText: perfect
PublicID: NIL
DescriptionText: perfect
...