返される文字列があり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);