在iOS中管理XML数据(Swift)

时间:2016-02-19 00:41:34

标签: ios xml swift parsing

我使用Zillow的基于Web的API来检索有关属性的数据。我成功地使用NSURLSession获取数据,但是,它是XML格式,我只有处理JSON的经验。

如何以更易读的形式组织这些数据,更具体地说,我如何获得年份(<yearBuilt>2007</yearBuilt>)值?

NSURLSession代码:

func data_request(){

    let url:NSURL = NSURL(string: url_to_request)!
    let session = NSURLSession.sharedSession()
    let request = NSMutableURLRequest(URL: url)
    request.HTTPMethod = "GET"
    request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData

    let task = session.dataTaskWithRequest(request) {
        (
        let data, let response, let error) in

        if (error == nil){
            //dataString is our XML data
            let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print(dataString)
        }
    }
    task.resume()
}

在控制台中打印的dataString(XML数据):
Optional(<?xml version="1.0" encoding="utf-8"?><SearchResults:searchresults xsi:schemaLocation="http://www.zillow.com/static/xsd/SearchResults.xsd http://www.zillowstatic.com/vstatic/9b53252/static/xsd/SearchResults.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SearchResults="http://www.zillow.com/static/xsd/SearchResults.xsd"><request><address>12572 Cherokee Ln</address><citystatezip>Galt, CA</citystatezip></request><message><text>Request successfully processed</text><code>0</code></message><response><results><result><zpid>25951952</zpid><links><homedetails>http://www.zillow.com/homedetails/12572-Cherokee-Ln-Galt-CA-95632/25951952_zpid/</homedetails><graphsanddata>http://www.zillow.com/homedetails/12572-Cherokee-Ln-Galt-CA-95632/25951952_zpid/#charts-and-data</graphsanddata><mapthishome>http://www.zillow.com/homes/25951952_zpid/</mapthishome><comparables>http://www.zillow.com/homes/comps/25951952_zpid/</comparables></links><address><street>12572 Cherokee Ln</street><zipcode>95632</zipcode><city>Galt</city><state>CA</state><latitude>38.299332</latitude><longitude>-121.267781</longitude></address><FIPScounty>6067</FIPScounty><useCode>SingleFamily</useCode><taxAssessmentYear>2015</taxAssessmentYear><taxAssessment>403012.0</taxAssessment><yearBuilt>2007</yearBuilt><lotSizeSqFt>663418</lotSizeSqFt><finishedSqFt>1527</finishedSqFt><bathrooms>2.0</bathrooms><bedrooms>3</bedrooms><totalRooms>6</totalRooms><zestimate><amount currency="USD">390005</amount><last-updated>02/17/2016</last-updated><oneWeekChange deprecated="true"></oneWeekChange><valueChange duration="30" currency="USD">-8580</valueChange><valuationRange><low currency="USD">370505</low><high currency="USD">409505</high></valuationRange><percentile>0</percentile></zestimate><localRealEstate><region name="Galt" id="24831" type="city"><zindexValue>281,700</zindexValue><links><overview>http://www.zillow.com/local-info/CA-Galt/r_24831/</overview><forSaleByOwner>http://www.zillow.com/galt-ca/fsbo/</forSaleByOwner><forSale>http://www.zillow.com/galt-ca/</forSale></links></region></localRealEstate></result></results></response></SearchResults:searchresults><!-- H:004 T:27ms S:1131 R:Thu Feb 18 16:33:36 PST 2016 B:4.0.25234-master.df01d52~hotfix_pre.361b6ff -->)(lldb)

XML格式更可读(在浏览器中查看时): enter image description here

2 个答案:

答案 0 :(得分:1)

Check this link

首先,委托&#34; NSXMLParserDelegate&#34;

其次,创建XML解析器并使委托成为自己的类

第三,使用parser的委托函数,例如didStartElement作为开始标记,foundCharacters作为标记内容。

请记住将您的xml字符串转换为NSData以供解析器阅读。

答案 1 :(得分:0)

李的回答是正确的。我只评论这个答案,以便偶然发现此问题的未来用户可以使用相关代码进行试用。这是我的代码:

1)在类

中声明NSXMLParserDelegate

2)声明NSXMLParser变量:
    var parser: NSXMLParser = NSXMLParser()

3)在viewDidAppear中//url_to_request is our URL we are receiving XML data from let url:NSURL = NSURL(string: url_to_request)! parser = NSXMLParser(contentsOfURL: url)! parser.delegate = self parser.parse()

4)使用XMLParser委托方法

func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [NSObject : AnyObject]) {
    eName = elementName
    //println(eName)
    if elementName == "yearBuilt" {
        self.yearBuilt = String()
    }
    if elementName == "useCode" {
        self.homeType = String()
    }
    if elementName == "lotSizeSqFt" {
        self.lotSizeSqFt = String()
    }
    if elementName == "finishedSqFt" {
        self.finishedSqFt = String()
    }
    if elementName == "bathrooms" {
        self.bathrooms = String()
    }
    if elementName == "bedrooms" {
        self.bedrooms = String()
    }
    if elementName == "totalRooms" {
        self.bedrooms = String()
    }

}

func parser(parser: NSXMLParser, foundCharacters string: String?) {
    let data = string!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
    if (!data.isEmpty) {
        //In this example, "yearBuilt", "useCode", etc, are all values within the <> tag.  
        if eName == "yearBuilt" {
            self.yearBuilt += data
            println("Year Built " + self.yearBuilt )
        }
        if eName == "useCode" {
            self.homeType += data
            println("Home Type " + self.homeType )
        }
        if eName == "lotSizeSqFt" {
            self.lotSizeSqFt += data
            println("lotSizeSqFt " + self.lotSizeSqFt )
        }
        if eName == "finishedSqFt" {
            self.finishedSqFt += data
            println("finishedSqFt " + self.finishedSqFt )
        }
        if eName == "bathrooms" {
            self.bathrooms += data
            println("bathrooms " + self.bathrooms )
        }
        if eName == "bedrooms" {
            self.bedrooms += data
            self.bedroomLabel.text = self.bedrooms
            println("bedrooms " + self.bedrooms )
        }

        if eName == "totalRooms" {
            self.totalRooms += data
            println("totalRooms " + self.totalRooms )
        }


    }
}

func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
    self.homeTypeLabel.text = self.homeType


    self.yearBuiltLabel.text = self.yearBuilt
    self.lotSizeLabel.text = self.lotSizeSqFt
    self.finishedSquareFeetLabel.text = self.finishedSqFt
    self.bathroomsLabel.text = self.bathrooms
    self.totalRoomsLabel.text = self.totalRooms



}