我有一个XML
返回给我的字符串,有时使用数字作为节点名称是无效的,例如:<2>
. 我想扫描NSString
保存 XML 的整个文件,然后搜索以下内容:
<numeric value // e.g. <1 or <2
</numeric value // e.g. </1 or </2
然后,我想在数字前加一个下划线,以便将无效更改为有效XML
,如下所示:
<_2>
</_2>
我想知道是否NSScanner
会完成这项工作,但我不确定如何解决这个问题。现在我只是在使用stringByReplacingOccurrencesOfString:withString:
,但我不得不硬编码要替换的数值,我认为这不是一个好主意。
更新:
我试了一下并使用了 NSRange。这是我想出的。它工作了大约 95%,但是在大型 xml 字符串上它会丢失最后几个</ >
标签,不知道为什么。任何意见或帮助改善这一点?
// Changeable string
NSMutableString *editable = [[[NSMutableString alloc] initWithString:str] autorelease];
// Number Formatter
NSLocale *l_en = [[[NSLocale alloc] initWithLocaleIdentifier: @"en_US"] autorelease];
NSNumberFormatter *f = [[[NSNumberFormatter alloc] init] autorelease];
[f setLocale: l_en];
// Make our first loop
NSUInteger count = 0, length = [str length];
NSRange range = NSMakeRange(0, length);
while(range.location != NSNotFound) {
// Find first character
range = [str rangeOfString: @"<" options:0 range:range];
// Make sure we have not gone too far
if (range.location+1 <= length) {
// Check the digit after this
NSString *after = [NSString stringWithFormat:@"%c", [str characterAtIndex:range.location+1]];
// Check if we return the number or not
if ([f numberFromString:after]) {
// Update the string
[editable insertString:@"_" atIndex:(range.location+1)+count];
count++;
}//end
}//end
// Check our range
if(range.location != NSNotFound) {
range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
}//end
}//end
// Our second part
NSUInteger slashLength = [editable length];
NSRange slashRange = NSMakeRange(0, slashLength);
while(slashRange.location != NSNotFound) {
// Find first character
slashRange = [editable rangeOfString: @"</" options:0 range:slashRange];
// Make sure we have not gone too far
if (slashRange.location+2 <= slashLength) {
// Check the digit after this
NSString *afterSlash = [NSString stringWithFormat:@"%c", [editable characterAtIndex:slashRange.location+2]];
// Check if we return the number or not
if ([f numberFromString:afterSlash]) {
// Update the string
[editable insertString:@"_" atIndex:(slashRange.location+2)];
}//end
}//end
// Check our range
if(slashRange.location != NSNotFound) {
slashRange = NSMakeRange(slashRange.location + slashRange.length, slashLength - ((slashRange.location+2) + slashRange.length));
}//end
}//end
NSLog(@"%@", editable);