【问题标题】:Using CDATA in html leaves the brackets at the end for iOS在 html 中使用 CDATA 在 iOS 的末尾留下括号
【发布时间】:2021-05-27 12:38:04
【问题描述】:

我有一个简单的html sn-p,看起来像这样:

let mystring = """
            <![CDATA[
            <body>
                <font size=+2>
                <p><b>Before proceeding:</b></p>
                <ul type="dash">
                    <li>Save a backup copy of the door configuration file</li><li>Disconnect all other Bluetooth devices</li></ul><br />
                <p><b>During upgrade:</b></p>
                <ul type="dash">
                    <li>Do not turn off phone screen, take calls, use other apps, or in any other way push the app to the background</li>
                </ul><br />
                <p><b>Are you sure you want to upgrade %1$@ firmware?</b></p>
                </font>
                </body>]]>
            """

我是这样解析的:

var htmlToAttributedString: NSMutableAttributedString? {
    guard let data = String(format: mystring, doorName).data(using: .utf8) else { return nil }
    do {
        return try NSMutableAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
    } catch {
        return nil
    }
}

结果是这样的(注意最后的 ]]>):

为什么brackets 仍然存在,而其他一切正常?它在测试Android 时工作正常,而且首先使用CDATA 也是为了Android。我该如何为iOS 工作?

【问题讨论】:

    标签: html ios swift parsing


    【解决方案1】:

    问题很可能是 CDATA 是 xml 而不是 html,这就是 NSAttributedString 无法正确处理它的原因。不幸的是,您的字符串不是正确的 xml 字符串,因此我们不能为此使用 XMLParser

    一种方法是使用正则表达式从字符串中去除 xml (CDATA)

    let htmlString = mystring.replacingOccurrences(of: "(<\\!\\[CDATA\\[|\\]\\]>)", 
                                                   with: "", 
                                                   options: .regularExpression)
       .trimmingCharacters(in: .whitespacesAndNewlines)
    

    【讨论】:

      猜你喜欢
      • 2011-05-17
      • 1970-01-01
      • 1970-01-01
      • 2019-04-24
      • 2019-07-13
      • 2020-02-24
      • 2012-07-26
      • 2012-09-29
      • 1970-01-01
      相关资源
      最近更新 更多