在聊天項目中發現內容裏面只要有< 和&這兩個字符,就顯示不了,後來查資料發現這是xml中的非法字符在作怪,解決的辦法是在編碼之前,也就是把文本信息轉化成xml格式之前先用實體引用替換了,message = [message stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
message = [message stringByReplacingOccurrencesOfString:@"<" withString:@"<"];;//實體引用;之後在xml解析的時候,在代理方法- (NSData *) parser:(NSXMLParser *)parser
resolveExternalEntityName:(NSString *)entityName
systemID:(NSString *)systemID {
static NSDictionary* entityTable = nil;
if (!entityTable) {
entityTable = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSData dataWithBytes:" " length:1], @"nbsp",
[NSData dataWithBytes:"&" length:1], @"&",
[NSData dataWithBytes:"\"" length:1], @"quot",
[NSData dataWithBytes:"<" length:1], @"<",
[NSData dataWithBytes:">" length:1], @"gt",
nil];
}
return [entityTable objectForKey:entityName];
}
裏面,把實體引用的字符再替換回來,就ok了!
實體引用
在 XML 中,一些字符擁有特殊的意義。
如果你把字符 "<" 放在 XML 元素中,會發生錯誤,這是因爲解析器會把它當作新元素的開始。
這樣會產生 XML 錯誤:
<message>if salary < 1000 then</message>
爲了避免這個錯誤,請用實體引用來代替 "<" 字符:
<message>if salary <
1000 then</message>
在 XML 中,有 5 個預定義的實體引用:
< | < | 小於 |
> | > | 大於 |
& | & | 和號 |
' | ' | 單引號 |
" | " | 引號 |
註釋:在 XML 中,只有字符 "<" 和 "&" 確實是非法的。大於號是合法的,但是用實體引用來代替它是一個好習慣。