Encode NSString for XML/HTML

后端 未结 14 1356
误落风尘
误落风尘 2020-11-28 04:25

Is there a way to HTML encode a string (NSString) in Objective-C, something along the lines of Server.HtmlEncode in .NET?

14条回答
  •  迷失自我
    2020-11-28 04:56

    I found the only way that uses only built-in functions (not manual parsing) and covers all cases. Requires AppKit/UIKit in addition to Foundation. This is Swift but can easily be Objective-C:

    func encodedForHTML() -> String {
    
        // make a plain attributed string and then use its HTML write functionality
        let attrStr = NSAttributedString(string: self)
    
        // by default, the document outputs a whole HTML element
        // warning: if default apple implementation changes, this may need to be tweaked
        let options: [NSAttributedString.DocumentAttributeKey: Any] = [
                .documentType: NSAttributedString.DocumentType.html,
                .excludedElements: [
                    "html",
                    "head",
                    "meta",
                    "title",
                    "style",
                    "p",
                    "body",
                    "font",
                    "span"
                ]
        ]
    
        // generate data and turn into string
        let data = try! attrStr.data(from: NSRange(location: 0, length: attrStr.length), documentAttributes: options)
        let str = String(data: data, encoding: .utf8)!
    
        // remove 

提交回复
热议问题