我有一个API调用,它将响应作为XML类型返回,我必须从xml数据中获取值并将其存储在String中,你能建议如何从xml响应中获取或映射值吗?
这是我来自服务器的示例响应:
responseString = <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
<email-address>xxx02v@gmail.com</email-address>
</person>
答案 0 :(得分:4)
对于原生XML解析,您可以NSXMLParser
和NSXMLParserDelegate
。它有许多方法可用于解析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)
}
}