Home > Blockchain >  How to use Swift XMLParser with span style tag
How to use Swift XMLParser with span style tag

Time:09-27

I am hoping to parse the following using a Swift XMLParser:

"<p> My <b> mother </b> has <span style=“color:blue”>blue</span> <i>eyes</i>.</p>"

I have created an XMLParser and implemented the delegate with a didStartElement method to print out the element name.

func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String: String] = [:]) {
        print(elementName)
}

I see all of the tags printed (p, b, i), but I never get the span value. How can I get it to find the span tag, and how can I get the "color:blue" value from it?

CodePudding user response:

The issue here seem to be the quotation marks in the string itself. is not valid here. After replacing it with " and ecaping it appropriatly it starts working:

let xml = "<p> My <b> mother </b> has <span style=\"color:blue\">blue</span> <i>eyes</i>.</p>"
let parser = XMLParser(data: xml.data(using: .utf8)!)
let delegate = ParserDelegagte()
parser.delegate = delegate
parser.parse()

class ParserDelegagte: NSObject, XMLParserDelegate{
    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
        print("start: ", elementName)
        print(attributeDict)
    }
    
    // 2
    func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
        print("end: ", elementName)
        print("end: ", qName ?? "empty")
    }
    
    // 3
    func parser(_ parser: XMLParser, foundCharacters string: String) {
        let data = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        print("found string: ", data)
        
    }
    
}

Output:

start:  p
[:]
found string:  My
start:  b
[:]
found string:  mother
end:  b
end:  empty
found string:  has
start:  span
["style": "color:blue"]
found string:  blue
end:  span
end:  empty
found string:  
start:  i
[:]
found string:  eyes
end:  i
end:  empty
found string:  .
end:  p
end:  empty

And regarding your 2nd question about acquiring the value of span atribute style:

func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
    
    if elementName == "span", let style = attributeDict["style"]{
        print(style)
    }
}
  • Related