gpt4 book ai didi

objective-c - 解析带有特殊字符的 XML 文件

转载 作者:数据小太阳 更新时间:2023-10-29 02:54:22 25 4
gpt4 key购买 nike

我尝试解析人员列表并用这些名称污染 UITableView。但是我要解析的人具有特殊字符(ä,ö,ü)。现在,如果我开始解析名称“Gött”,那么之后就是“ött”。真的很奇怪,有什么想法吗?非常感谢!

-(id) loadXMLByURL:(NSString *)urlString
{
tweets = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
parser = [[NSXMLParser alloc] initWithData:data];
parser.delegate = self;
[parser parse];
return self;
}

- (void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementname namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementname isEqualToString:@"lehrer"])
{
currentTweet = [Tweet alloc];
}
}

- (void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementname namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementname isEqualToString:@"name"])
{
currentTweet.content = currentNodeContent;
}
if ([elementname isEqualToString:@"vorname"])
{
currentTweet.vorname = currentNodeContent;
}
if ([elementname isEqualToString:@"created_at"])
{
currentTweet.dateCreated = currentNodeContent;
}
if ([elementname isEqualToString:@"lehrer"])
{
[tweets addObject:currentTweet];
[currentTweet release];
currentTweet = nil;
[currentNodeContent release];
currentNodeContent = nil;
}
}

- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
currentNodeContent = (NSMutableString *) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

- (void) dealloc
{
[parser release];
[super dealloc];
}

@end

最佳答案

这是正常行为 - parser:foundCharacters 可以为一个字符串调用多次(并且往往是为重音字符调用)。您的字符串直到元素末尾才完整,因此请存储它们并在到达 block 末尾时使用完整的字符串。它在 foundCharacters 的文档中

Apple developer docs on NSXMLParser

The parser object may send the delegate several parser:foundCharacters: messages to report the characters of an element. Because string may be only part of the total character content for the current element, you should append it to the current accumulation of characters until the element changes.

根据问题编辑:

一般来说代码没问题,但在字符函数中,做

- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if(nil == currentNodeContent)
currentNodeContent = [[NSMutableString alloc] initWithString:string];
else
[currentNodeContent appendString:string];
}

然后在 didStart 和 didEnd 中调用一个方法来检查字符串是否为 nil,首先执行您要对它执行的操作,然后释放字符串(并将其设为 null)。

字符串在新元素的开头(即开头 < 之前的文本)和末尾(< 之前的文本位)结束

关于objective-c - 解析带有特殊字符的 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10388850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com