无法使用SWIFT 2从机箱标签rss xml中提取url值

时间:2016-07-03 02:01:24

标签: ios xml xcode swift2 rss

我在RSS Feed中提取机箱标签的url内容时遇到了困难。我在Xcode 7 Swift 2上开发。

我的NSXMLDelegate解析代码如下:

func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
    eName = elementName
    if elementName == "item" {
        postTitle = String()
        postLink = String()
        postDate = String()
        postImageUrl = String()
    }
}

以下是负责解析RSS XML提要的相关源代码

func parser(parser: NSXMLParser, foundCharacters string: String) {
    let data = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
    if (!data.isEmpty) {
        print("eName Start")
        print(eName)
        print(data,"DATAAAA")
        print("eName END")
        if eName == "title" {
            postTitle += data//TEST OK
        } else if eName == "link" {
            postLink += data//TEST OK
        } else if eName == "pubDate" {

            postDate += data//TEST OK
        }
        else if eName == "enclosure"{
            print(data)//THIS IS EMPTY WHY !?
            print("enc details")
            postImageUrl += data
        }
    }
}

如上所述,我能够从RSS Feed中提取“title”,“pubDate”和“link”标签,但不能从机箱标签中提取。 当我在检测到“enclosure”时尝试转储数据时,返回的数据为空。

我怀疑问题出在这行代码中,我没有正确过滤RSS对象。

let data = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

RSS源的来源是:www.securitymagazine.com/rss/15

有人可以提供一些见解吗?我非常感激 !

1 个答案:

答案 0 :(得分:2)

"围栏" RSS中的元素是这样的:

<enclosure url="http://www.securitymagazine.com/ext/resources/SEC/2016/0616/Boschdata.jpg?1467317413" type="image/jpeg" length="280480"/>

url包含在元素的属性中,而不是开始标记后面的字符(#text)数据。您可以在parser(_:didStartElement:...)方法中访问元素属性。所以,你需要像这样修改方法:

func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
    eName = elementName
    switch elementName {
    case "item":
        postTitle = String()
        postLink = String()
        postDate = String()
        postImageUrl = String()
    case "enclosure":
        if let urlString = attributeDict["url"] {
            //...use `urlString` appropriately
            print(urlString)
            print("enc details")
            postImageUrl += urlString
        } else {
            print("malformed element: enclosure without url attribute")
        }
    //...cases for other element name
    default:
        //...
        break
    }
}