2

I want to get the URL of image from this XML:

<description>
<![CDATA[
<div><a href='http://www.ynet.co.il/articles/0,7340,L-4794118,00.html'><img src='http://images1.ynet.co.il/PicServer4/2016/04/20/6955445/small2.jpg' alt='null' title='null' border='0' width='100' height='56'></a></div>בפוליטיקה, בכלכלה, בביטחון, במשפט, בתרבות, באקדמיה. המתח העדתי עדיין איתנו בכל פינה. למה הגיעו כל כך מעט מזרחיים למוקדי הכוח בישראל? הנתונים המלאים, הניתוח והפרשנויות יתפרסמו ב-ynet בחג. צפו בהצצה
]]>
</description>

This is my code. I got empty array what's wrong with my code and what is the solution for my problem.

class ImageParser: NSObject, NSXMLParserDelegate{

    var itemsStarted = false;
    var descriptionStarted  = false;
    var divStarted = false;
    var aStarted = false;
    var inImage = false;
    var images:[String] = [];

    func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
        if(elementName == "item"){
            itemsStarted = true;
        }

        if(itemsStarted && elementName == "description"){
            descriptionStarted = true;
        }

        if(descriptionStarted && elementName == "div"){
            divStarted = true;
        }

        if(divStarted && elementName == "a"){
            inImage = true;
        }

        if(inImage && elementName == "img"){
            images.append(attributeDict["src"]!);
        }
    }

    func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
        if(elementName == "img"){
            inImage = false;
        }
    }
  }
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Possible duplicate of [Using NSXMLParser with CDATA](http://stackoverflow.com/questions/1095782/using-nsxmlparser-with-cdata) – JAL Apr 20 '16 at 20:06
  • you can show me how to use found CDATA function in swift ? i want extract the url of image from this block – Neria Jerafi Apr 21 '16 at 04:16
  • 1
    @JAL :Not a duplicate since the post you referenced is in Obj-C and not swift...The answer is sort of there. – Ilan Kutsman Apr 21 '16 at 07:22

1 Answers1

2

NSXMLParser ignores anything within CDATA, so if your CDATA contains valid xml tags, what you need to do is basicly is run another instance of parser on the text inside CDATA.

this might help https://github.com/hunkier/XMLParser-Swift/blob/master/XMLParser.swift

also try adding this method to your code in swift 2:

func parser(parser: NSXMLParser!, foundCDATA CDATABlock: NSData!) {
            var datastring = String(CDATABlock: NSData!, encoding: NSUTF8StringEncoding);
}

Use NSString instead of String in earlier version of swift...syntax is the same

Ilan Kutsman
  • 469
  • 3
  • 9