过滤掉NSXMLDocument中的BOM字符

时间:2012-11-06 20:54:23

标签: objective-c xml nsxmldocument nsxmlelement

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];

我的问题是:

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

1 个答案:

答案 0 :(得分: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文档的选项设置为none。您可能希望根据自己的目的进行更改。

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