0

我正在尝试从 xml NSData *xmlData = [request responseData]; 获取字符串

NSString *stringData = [[NSString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding];

loginParsingDelegate *loginResultParser = [[loginParsingDelegate alloc] init];
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:xmlData];
[parser setDelegate:loginResultParser];
[parser parse];

 NSString *filePath = [NSString stringWithFormat:@"%@/conf.plist", DOCUMENTS_FOLDER] ;
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] init];
   NSString *city = [parsingResult objectForKey:@"city"];

但是当有口音时,这会出错...例如:Sao Paulo = "Sao Paulo" but São Paulo I'm getting "ão Paulo"

怎么了?xml返回正确...

4

1 回答 1

4

我用一个简单的 XML 字符串启动了你的代码

<city>São Paulo</city>

看起来您在委托中没有正确处理字符。因为这个 XML- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string实际上被调用了两次:第一次用“S”,第二次用“ão Paulo”。您应该处理这种情况,因为无论如何这种方法不能保证一次性为您提供完整的字符串。

解析器:找到字符:

由解析器对象发送,以向其委托提供表示当前元素的全部或部分字符的字符串。

更新:

一个极其简单的例子。给定一个 XML

<cities>
    <city>São Paulo</city>
    <city>Rio de Janeiro</city>
    <city>Salvador</city>
</cities>

我们可以制作这样的解析器

@implementation ParserClass {
    NSMutableString *elementText;
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    elementText = nil; // we are not handling elements other than "city"
    if ([elementName isEqualToString:@"city"]) {
        elementText = [NSMutableString new]; // prepare an empty string for city name
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    [elementText appendString:string]; // append new characters to the element text
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    // element did end - string now contains text of the element
    if ([elementName isEqualToString:@"city"]) {
        NSString *cityName = [elementText copy]; // now we have a full city name
        ...
    }
}

...

@end

请注意,这不是解析任何 XML 的通用代码。如果您了解 SAX 解析的工作原理,您当然可以编写一门课程。

于 2012-11-09T01:21:32.100 回答