做項目時曹宴,在解析含有中文信息的XML數(shù)據(jù)時覆山,總是時不時返回nil植锉。
斷點定位到 xmlParseMemory([data bytes], (int)[data length]); 這個方法上。
解析不對一般應該編碼的問題幸斥。所以匹摇,找一個能夠指定編碼的方法替代他就可以了。
下面是我修改過的代碼:
- (id)initWithData:(NSData *)data options:(NSUInteger)mask error:(NSError **)error
{
if (data == nil || [data length] == 0)
{
if (error) *error = [NSError errorWithDomain:@"DDXMLErrorDomain" code:0 userInfo:nil];
return nil;
}
// Even though xmlKeepBlanksDefault(0) is called in DDXMLNode's initialize method,
// it has been documented that this call seems to get reset on the iPhone:
// http://code.google.com/p/kissxml/issues/detail?id=8
//
// Therefore, we call it again here just to be safe.
xmlKeepBlanksDefault(0);
/** 下邊注釋的方法是這里原有的方法睡毒,這個方法是我加的来惧,因為返回數(shù)據(jù)編碼的是GBK的演顾,所以只能指定編碼解析XML數(shù)據(jù) */
xmlDocPtr doc = xmlReadMemory([data bytes],(int)[data length],NULL,"gbk",XML_PARSE_RECOVER);
// xmlDocPtr doc = xmlParseMemory([data bytes], (int)[data length]);
if (doc == NULL)
{
if (error) *error = [NSError errorWithDomain:@"DDXMLErrorDomain" code:1 userInfo:nil];
return nil;
}
return [self initWithDocPrimitive:doc owner:nil];
}
修改過后供搀,果然可以了隅居。
這個方法應該可以應付不同編碼的XML數(shù)據(jù)了。