我正在尝试使用é,ñ等字符解析XML我使用UTF8作为编码..
我已经尝试将编码更改为 NSISOLatin1StringEncoding ,但它不起作用
代码是:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//NSLog(@"DONE. Received Bytes: %d", [webData length]);
NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
// NSLog(theXML);
[theXML release];
if( xmlParser )
{
[xmlParser release];
}
xmlParser = [[NSXMLParser alloc] initWithData: webData];
[xmlParser setDelegate:self];
[xmlParser setShouldResolveExternalEntities:YES];
[xmlParser parse];
if (connection) {
[connection release];
}
}
-(void)callWS {
NSString *url = @"theUrlHere";
NSMutableURLRequest *request =[[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"GET"];
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) {
webData = [[NSMutableData data] retain];
}
当我收到xml回复时...带有特殊字符的结果显示错误...
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if(!soapResults)
{
....//the soapResults here appears wrong when It has special chars...
}
示例:Caperuçú出现çú,Indianópolis出现ópolis
答案 0 :(得分:3)
请参阅parser:foundCharacters:
委托方法的文档:
解析器对象可以发送几个委托 parser:foundCharacters:报告一个字符的消息 元件。因为字符串可能只是整个字符的一部分 当前元素的内容,您应该将其附加到当前元素 字符的积累直到元素改变。
我认为您的代码不会累积字符,只会使用最后 parser:foundCharacters:
调用的结果。
以下示例程序使用您的输入字符串显示此效果:
-(void)parse
{
NSString *xmlString = @"<a><b>Indianópolis</b><c>Caperuçú</c></a>";
NSData *xmlData = [xmlString dataUsingEncoding:NSUTF8StringEncoding];
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:xmlData];
parser.delegate = self;
[parser parse];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
NSLog(@"didStartElement: %@", elementName);
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
NSLog(@"didEndElement: %@", elementName);
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
NSLog(@"foundCharacters: %@", string);
}
输出:
didStartElement: a
didStartElement: b
foundCharacters: Indian
foundCharacters: ópolis
didEndElement: b
didStartElement: c
foundCharacters: Caperu
foundCharacters: çú
didEndElement: c
didEndElement: a
所以这不是编码问题。