与NSData一起使用时出现NSXML解析错误

时间:2012-01-08 16:40:07

标签: iphone ios xml nsurlconnection nsxmlparser

我有一个包含产品子集列表的简单XML文件。当我从iOS App包中加载文件并通过解析器发送它:initWithNSURL时,NSURL指向本地文件,它正确解析。

但是,如果我通过NSURLConnection下载相同的文件并将其传递给具有initWithData的解析器,则解析将失败。我可以确认数据是否正确下载,因为如果我执行NSString *temp = [NSString stringWithUTF8String:[downloadedData bytes]];输出的字符串是正确的。 我有一个人觉得有时候在某个地方进行编码,有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我的朋友做解析器工作,     NSString * xmlData = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

xmlData应该是这样的     
         ABC      而我的朋友只是分析字符串,这是工作

我用libxml2用

解析xml
xmlTextReaderPtr reader = xmlReaderForMemory([data bytes], [data length], NULL, NULL,             (XML_PARSE_NOBLANKS | XML_PARSE_NOCDATA | XML_PARSE_NOERROR | XML_PARSE_NOWARNING));

if (reader != NULL) {
    ret = xmlTextReaderRead(reader);
    while (ret == 1) {
        const xmlChar *name, *value;

        name = xmlTextReaderConstName(reader);
        if (name == NULL)
        name = BAD_CAST "--";
        NSString *Name = [NSString stringWithCString:(const char*)name encoding:NSUTF8StringEncoding];

        value = xmlTextReaderConstValue(reader);
        if (value == NULL)
            value = BAD_CAST "\n";
        NSString *Value = [NSString stringWithCString:(const char*)value encoding:NSUTF8StringEncoding];
        NSLog("%d %d %@ %d %@", 
        xmlTextReaderDepth(reader),
        xmlTextReaderNodeType(reader),
        Name,
        xmlTextReaderIsEmptyElement(reader),
        Value);



        ret = xmlTextReaderRead(reader);
    }
    xmlFreeTextReader(reader);
  }

,结果也是正确的