anonymox anonymox - 4 years ago 164
Swift Question

Replacing html tag with null in XML string

I want to replace

<![CDATA[
tag in xml string with null but I don't know how to find or grab this tag using regular expression in swift 2.0

My xml string is something like :

let xmlvar = "<description>" +
"<![CDATA[<img data-toggle='tooltip' src='uploads/posts/thumbnails/92-9-6-khatami-5-52-on.jpg' alt='123'/><span>123</span>]]>" +
"</description>


which I need to remove
<![CDATA[
and it's end part
]]
from xmlvar

Update :

how can I use Regular expression on xml data from rss feed ?
I'm facing
xml is not convertible to NSString
error

here is my code :

let url = NSURL(string: "http://razavitv.aqr.ir/index/rss/2")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
let xml = SWXMLHash.parse(data!)
let processedString = (xml as NSString).stringByReplacingOccurrencesOfString("<![CDATA[", withString: "").stringByReplacingOccurrencesOfString("]]", withString: "") as String
let appName = xml["rss"]["channel"]["item"][0]["title"].element!.text!
let appUrl = xml["rss"]["channel"]["item"][0]["description"]["img"].element!.attributes["src"]
let ap = Apps(name: appName , img : appUrl)
self.tableData.append(ap)
self.tableView.reloadData()
}
task.resume()


Any suggestion how ?

Answer Source

You can use NSString's stringByReplacingOccurrencesOfString functionality:

let processedString = (xmlvar as NSString).stringByReplacingOccurrencesOfString("<![CDATA[", withString: "").stringByReplacingOccurrencesOfString("]]", withString: "") as String

You convert to NSString, apply the two replacements, and then get back to String

Or you can use a regular expression:

// we know for sure the regex is a valid string, thus the forced try, otherwise forced stuff is not recommended
let regex = try! NSRegularExpression(pattern: "\\<\\!\\[CDATA\\[|\\]\\]", options: NSRegularExpressionOptions.CaseInsensitive)
let len = xmlvar.lengthOfBytesUsingEncoding(NSStringEncoding(NSUTF8StringEncoding))
let processedString = regex.stringByReplacingMatchesInString(xmlvar, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, len), withTemplate: "")
print(processedString)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download