0

XML 文件中某些元素的 stringValue 中包含 BOM 字符。xml 文件被标记为 UTF-8 编码。

其中一些字符位于字符串的开头(因为它应该来自我所读到的内容),但有些字符位于字符串的中间(可能来自编写 xml 文件的人的格式错误的字符串?)。

我打开文件:

NSURL *furl = [NSURL fileURLWithPath:fileName];
if (!furl) {
    NSLog(@"Error: Can't open NML file '%@'.", fileName);

    return kNxADbReaderTTError;
}

NSError *err=nil;

NSXMLDocument *xmlDoc = [[NSXMLDocument alloc] initWithContentsOfURL:furl options:NSXMLNodeOptionsNone error:&err];

我以这种方式查询元素:

NSXMLElement *anElement;
NSString *name;
...
NSString *valueString = [[anElement attributeForName:name] stringValue];

我的问题是:

我打开文件错了吗?文件格式不正确?我查询元素的字符串值是否错误?如何过滤掉这些字符?

4

1 回答 1

0

在修复另一个问题时,我发现了一种从 NSXMLDocument 源中过滤掉不需要的字符的相对干净的方法。将其粘贴在这里以防万一有人遇到类似问题:

@implementation NSXMLDocument (FilterIllegalCharacters)

    - (NSXMLDocument *)initWithDataAndIgnoreIllegalCharacters:(NSData *)data illegalChars:(NSCharacterSet *)illegalChars error:(NSError **)error{
    // -- Then, read the resulting XML string.
    NSMutableString *str = [[NSMutableString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    // -- Go through the XML, only caring about attribute value strings
    NSMutableArray *charactersToRemove = [NSMutableArray array];
    NSUInteger openQuotes = NSNotFound;
    for (NSUInteger pos = 0; pos < str.length; ++pos) {
        NSUInteger currentChar = [str characterAtIndex:pos];

        if (currentChar == '\"') {
            if (openQuotes == NSNotFound) {
                openQuotes = pos;
            }
            else {

                openQuotes = NSNotFound;
            }
        }
        else if (openQuotes != NSNotFound) {
            // -- If we find an illegal character, we make a note of its position.
            if ([illegalChars characterIsMember:currentChar]) {
                [charactersToRemove addObject:[NSNumber numberWithLong:pos]];
            }
        }
    }

    if (charactersToRemove.count) {
        NSUInteger index = charactersToRemove.count;

        // -- If we have characters to fix, we work thru them backwards, in order to not mess up our saved positions by modifying the XML.
        do {
            --index;

            NSNumber *characterPos = charactersToRemove[index];
            [str replaceCharactersInRange:NSMakeRange(characterPos.longValue, 1) withString:@""];
        }
        while (index > 0);

        // -- Finally we update the data with our corrected version
        data = [str dataUsingEncoding:NSUTF8StringEncoding];
    }

    return [[NSXMLDocument alloc] initWithData:data options:NSXMLNodeOptionsNone 

    error:error];
}

@end

你可以传递任何你想要的字符集。请注意,这会将读取 XML 文档的选项设置为无。您可能希望出于自己的目的更改此设置。

这只会过滤属性字符串的内容,这是我的格式错误的字符串的来源。

于 2013-07-11T19:12:45.730 回答