iPhone删除<! - [CDATA - >

时间:2010-07-29 09:20:17

标签: iphone string cdata

我正在阅读xml,最后需要在我的结果中删除CDATA信息

例如:我得到:

 "<![CDATA[iPhone 4-Rückgaberecht: Deutsche Telekom kulant]]>"

只需要“iPhone 4-Rückgaberecht:Deutsche Telekom kulant”

THX 克里斯

编辑您的答案: 我没有使用NSXMLParser(这就是我创建自己的解析器的原因)

找到一些建议:

- (NSString *)stringByDecodingXMLEntities;
but dont know how to implement. I always get
> YourController may not respond to '-stringByDecodingXMLEntities" <

4 个答案:

答案 0 :(得分:2)

好的,我解决了这个问题:

 NSMutableString* resultString;


- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)s {
   resultString = [[NSMutableString alloc] init];
    [resultString appendString:s];
}

- (NSString*)convertEntiesInString:(NSString*)s {
    if(s == nil) {
    NSLog(@"ERROR : Parameter string is nil");
    }
    NSString* xmlStr = [NSString stringWithFormat:@"<d>%@</d>", s];
    NSData *data = [xmlStr dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    NSXMLParser* xmlParse = [[NSXMLParser alloc] initWithData:data];
    [xmlParse setDelegate:self];
    [xmlParse parse];
    NSString* returnStr = [[NSString alloc] initWithFormat:@"%@",resultString];
  return returnStr;
}

调用:myConvertedString = [self convertEntiesInString:myOriginalString];

答案 1 :(得分:1)

使用

  • (void)解析器:(NSXMLParser *)解析器foundCDATA:(NSData *)CDATABlock

方法而不是

  • (void)parser:(NSXMLParser *)解析器foundCharacters:(NSString *)string

多数民众赞成

答案 2 :(得分:1)

你可以试试正则表达式

<!\[CDATA\[(.*)\]\]>替换为$1

答案 3 :(得分:0)

如果您已经拥有String in String格式,可以将其删除:

//Declare what you wish to remove
NSString * suffixTorRemove = @"<![CDATA[";
NSString * prefixToRemove = @"]]>";

//Now create a new string which uses your existing string and removes the declared occurrences above
NSString * newString = [yourString stringByReplacingOccurrencesOfString:suffixTorRemove withString:@""];
//Now the first part has changed, time to remove the second part
NSString * newString2 = [newString stringByReplacingOccurrencesOfString:prefixTorRemove withString:@""];

快速而简单: - )