如何解析XML数据并将其存储在swift中的字符串值中

时间:2016-03-22 12:06:29

标签: ios xml string swift

我有一个API调用,它将响应作为XML类型返回,我必须从xml数据中获取值并将其存储在String中,你能建议如何从xml响应中获取或映射值吗?

这是我来自服务器的示例响应:

responseString = <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
<email-address>xxx02v@gmail.com</email-address>
</person>

1 个答案:

答案 0 :(得分:4)

对于原生XML解析,您可以NSXMLParserNSXMLParserDelegate。它有许多方法可用于解析XML数据

使用NSXMLParserDelegate的有用方法

    - parserDidStartDocument:
    - parserDidEndDocument:
    - parser:didStartElement:namespaceURI:qualifiedName:attributes:
    - parser:didEndElement:namespaceURI:qualifiedName:
    - parser:foundCharacters:

Apple Doc: NSXMLParser
Apple Doc: NSXMLParserDelegate

示例

var parser = NSXMLParser()
var posts = NSMutableArray()
var elements = NSMutableDictionary()
var element = NSString()
var title1 = NSMutableString()
var date = NSMutableString()

func beginParsing()
    {
        posts = []
        parser = NSXMLParser(contentsOfURL:(NSURL(string:"http://images.apple.com/main/rss/hotnews/hotnews.rss"))!)!
        parser.delegate = self
        parser.parse()
    }

func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String])
    {
        element = elementName
        if (elementName as NSString).isEqualToString("item")
        {
            elements = NSMutableDictionary()
            elements = [:]
            title1 = NSMutableString()
            title1 = ""
            date = NSMutableString()
            date = ""
        }
    }

func parser(parser: NSXMLParser!, foundCharacters string: String!)
    {
        if element.isEqualToString("title") {
            title1.appendString(string)
        } else if element.isEqualToString("pubDate") {
            date.appendString(string)
        }
    }

func parser(parser: NSXMLParser!, didEndElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!)
    {
        if (elementName as NSString).isEqualToString("item") {
            if !title1.isEqual(nil) {
                elements.setObject(title1, forKey: "title")
            }
            if !date.isEqual(nil) {
                elements.setObject(date, forKey: "date")
            }

            posts.addObject(elements)
        }
    }

完整演示示例:
NSXML Parser Swift 1
NSXML Parser Swift 2