当前位置:  开发笔记 > 编程语言 > 正文

为XML/HTML编码NSString

如何解决《为XML/HTML编码NSString》经验,为你挑选了5个好方法。

有没有办法在objective-c中对字符串(NSString)进行HTML编码,这与.NET中的Server.HtmlEncode一致?

谢谢!



1> thesamet..:

没有NSString方法可以做到这一点.你必须编写自己的函数来进行字符串替换.只需进行以下替换就足够了:

'&'=>"&"

'''=>"""

'\''=>"'"

'>'=>">"

'<'=>"<"

这样的事情应该做(没试过):

[[[[[myStr stringByReplacingOccurrencesOfString: @"&" withString: @"&"]
 stringByReplacingOccurrencesOfString: @"\"" withString: @"""]
 stringByReplacingOccurrencesOfString: @"'" withString: @"'"]
 stringByReplacingOccurrencesOfString: @">" withString: @">"]
 stringByReplacingOccurrencesOfString: @"<" withString: @"<"];


此解决方案并非在所有情况下都有效.我最近遇到了一个包含字符0xE28099的UTF-8字符串的错误,该字符转换为UTF-8 2019或"右单引号".在上面的例子中没有处理这样的扩展字符,并且导致客户端服务器出错(因为它们超出了规范).上面的示例在大多数情况下工作,但不是全部.
快速说明一下,如果你要在1个运行循环内的很多XML/HTML上执行很多这些转义,那么不要忘记将每个编码包装在一个`NSAutoreleasePool`中!

2> Tod Cunningh..:

我接受了Mike的工作并将其转换为NSMutableString和NSString的类别

使用以下命令为NSMutableString创建一个类别:

- (NSMutableString *)xmlSimpleUnescape
{
    [self replaceOccurrencesOfString:@"&"  withString:@"&"  options:NSLiteralSearch range:NSMakeRange(0, [self length])];
    [self replaceOccurrencesOfString:@""" withString:@"\"" options:NSLiteralSearch range:NSMakeRange(0, [self length])];
    [self replaceOccurrencesOfString:@"'" withString:@"'"  options:NSLiteralSearch range:NSMakeRange(0, [self length])];
    [self replaceOccurrencesOfString:@"'"  withString:@"'"  options:NSLiteralSearch range:NSMakeRange(0, [self length])];
    [self replaceOccurrencesOfString:@"’" withString:@"'"  options:NSLiteralSearch range:NSMakeRange(0, [self length])];
    [self replaceOccurrencesOfString:@"–" withString:@"-"  options:NSLiteralSearch range:NSMakeRange(0, [self length])];
    [self replaceOccurrencesOfString:@">"   withString:@">"  options:NSLiteralSearch range:NSMakeRange(0, [self length])];
    [self replaceOccurrencesOfString:@"<"   withString:@"<"  options:NSLiteralSearch range:NSMakeRange(0, [self length])];

    return self;
}

- (NSMutableString *)xmlSimpleEscape
{
    [self replaceOccurrencesOfString:@"&"  withString:@"&"  options:NSLiteralSearch range:NSMakeRange(0, [self length])];
    [self replaceOccurrencesOfString:@"\"" withString:@""" options:NSLiteralSearch range:NSMakeRange(0, [self length])];
    [self replaceOccurrencesOfString:@"'"  withString:@"'" options:NSLiteralSearch range:NSMakeRange(0, [self length])];
    [self replaceOccurrencesOfString:@">"  withString:@">"   options:NSLiteralSearch range:NSMakeRange(0, [self length])];
    [self replaceOccurrencesOfString:@"<"  withString:@"<"   options:NSLiteralSearch range:NSMakeRange(0, [self length])];

    return self;
}

使用以下命令为NSString创建一个类别:

- (NSString *)xmlSimpleUnescapeString
{
    NSMutableString *unescapeStr = [NSMutableString stringWithString:self];

    return [unescapeStr xmlSimpleUnescape];
}


- (NSString *)xmlSimpleEscapeString
{
    NSMutableString *escapeStr = [NSMutableString stringWithString:self];

    return [escapeStr xmlSimpleEscape];
}

*Swift 2.0版本*

Objective-C版本更高效,因为它对字符串进行了可变操作.但是,这是一个简单转义的快捷方法:

extension String
{
    typealias SimpleToFromRepalceList = [(fromSubString:String,toSubString:String)]

    // See http://stackoverflow.com/questions/24200888/any-way-to-replace-characters-on-swift-string
    //
    func simpleReplace( mapList:SimpleToFromRepalceList ) -> String
    {
        var string = self

        for (fromStr, toStr) in mapList {
            let separatedList = string.componentsSeparatedByString(fromStr)
            if separatedList.count > 1 {
                string = separatedList.joinWithSeparator(toStr)
            }
        }

        return string
    }

    func xmlSimpleUnescape() -> String
    {
        let mapList : SimpleToFromRepalceList = [
            ("&",  "&"),
            (""", "\""),
            ("'", "'"),
            ("'",  "'"),
            ("’", "'"),
            ("–", "-"),
            (">",   ">"),
            ("<",   "<")]

        return self.simpleReplace(mapList)
    }

    func xmlSimpleEscape() -> String
    {
        let mapList : SimpleToFromRepalceList = [
            ("&",  "&"),
            ("\"", """),
            ("'",  "'"),
            (">",  ">"),
            ("<",  "<")]

        return self.simpleReplace(mapList)
    }
}

我本可以使用NSString桥接功能来编写与NSString版本非常相似的东西,但我决定更加开心.



3> Chris Lundie..:

我使用的是Google Toolbox for Mac(适用于iPhone).特别是,请参阅GTMNSString + HTML.h和GTMNSString + XML.h中对NSString的添加.



4> e.James..:

对于URL编码:

NSString * encodedString = [originalString
      stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];

有关详细信息,请参阅Apple的NSString文档.

对于HTML编码:

查看CFXMLCreateStringByEscapingEntities,它是Core Foundation XML库的一部分,但仍应该这样做.


我相信这是URL编码,而不是HTML编码.

5> 小智..:

同样的例程忘记了十六进制数字.这是我提出的例行程序:

- (NSString*)convertEntities:(NSString*)string
{

NSString    *returnStr = nil;

    if( string )
    {
        returnStr = [ string stringByReplacingOccurrencesOfString:@"&" withString: @"&"  ];

        returnStr = [ returnStr stringByReplacingOccurrencesOfString:@""" withString:@"\""  ];

        returnStr = [ returnStr stringByReplacingOccurrencesOfString:@"'" withString:@"'"  ];

        returnStr = [ returnStr stringByReplacingOccurrencesOfString:@"9" withString:@"'"  ];

        returnStr = [ returnStr stringByReplacingOccurrencesOfString:@"’" withString:@"'"  ];

        returnStr = [ returnStr stringByReplacingOccurrencesOfString:@"–" withString:@"'"  ];

        returnStr = [ returnStr stringByReplacingOccurrencesOfString:@">" withString:@">"  ];

        returnStr = [ returnStr stringByReplacingOccurrencesOfString:@"<" withString:@"<"  ];

        returnStr = [ [ NSString alloc ] initWithString:returnStr ];
    }

    return returnStr;
}

推荐阅读
mobiledu2402852413
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有