NSXMLParser在Objective-C中解析数字和中文字符

fmc*_*han 0 objective-c special-characters nsxmlparser ios

这是我的XML:

<?xml version="1.0" encoding="UTF-8"?>
<Tests>
    <Test case="1">
        <str>200000</str>
    </Test>
    <Test case="2">
        <str>200thousand</str>
    </Test>
    <Test case="3">
        <str>?20?</str>
    </Test>
    <Test case="4">
        <str>20?</str>
    </Test>
</Tests>
Run Code Online (Sandbox Code Playgroud)

这是解析器的一部分,这是非常标准的,因为我在大多数教程中都找到了它:

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { 
    if(!currentElementValue)
        currentElementValue = [[NSMutableString alloc] initWithString:string];
    else
        currentElementValue = 
            (NSMutableString *) [string stringByTrimmingCharactersInSet:
                [NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
Run Code Online (Sandbox Code Playgroud)

然后我使用这一行将每个currentElementValue解析为testObj的每个变量

[testObj setValue:currentElementValue forKey:elementName];
Run Code Online (Sandbox Code Playgroud)

代码成功地将XML解析为testObj.然而,问题是在情况4中,"20"消失了.即一旦元素以数字开头,然后跟随汉字,数字就会消失.

此外,如果我使用:

        [currentElementValue appendString:string];
Run Code Online (Sandbox Code Playgroud)

代替:

        currentElementValue = 
            (NSMutableString *) [string stringByTrimmingCharactersInSet:
                [NSCharacterSet whitespaceAndNewlineCharacterSet]];
Run Code Online (Sandbox Code Playgroud)

元素可以显示所有字符,但以许多空格开头.

我想弄清楚为什么数字消失了,并寻找解决方案来显示没有空格领先的所有字符.

提前感谢您提供的任何帮助!

Mar*_*n R 5

请参阅parser:foundCharacters:委托方法的文档:

解析器对象可以向委托发送几个解析器:foundCharacters:消息来报告元素的字符.因为字符串可能只是当前元素的总字符内容的一部分,所以应该将其附加到当前字符的累积,直到元素更改为止.

所以,你必须使用appendStringfoundCharacters.额外的空白可能是因为您没有重置当前字符串didStartElement并且didEndElement:

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
     currentElementValue = nil;
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
     if (currentElementValue) {
         NSLog(@"%@ = %@", elementName, currentElementValue);
         currentElementValue = nil;
     }
}
Run Code Online (Sandbox Code Playgroud)

如有必要,您可以删除不需要的空白区域didEndElement.