XMLParser在iphone上重复元素

时间:2012-10-01 22:46:45

标签: iphone ios xml

我有一个NSXMLParser,它正在解析一个XML文件,使用Apple的事件驱动的XML处理实现。

我已经正确设置了它,但是当我进行实际的解析时,它会在解析时遍历同一个元素两次。

我的代码如下所示:

AppDelegate *myApp = (AppDelegate*)[[UIApplication sharedApplication] delegate];
NSData *tempData = [myApp.stringDetails dataUsingEncoding:NSUTF8StringEncoding];
NSString *textFields = [NSString string];
NSXMLParser *parser = [[NSXMLParser alloc]initWithData:tempData];
[parser setDelegate: self];
if ([parser parse]!= YES) {
    NSLog(@"%@", parser.parserError.description);
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName     namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
    textFields = elementName;
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if ([textFields isEqualToString:@"firstName"]) {
        [firstName setText:string];
        NSLog(@"first name is %@", string);
        return;
    }
    if ([textFields isEqualToString:@"lastName"]) {
        [lastName setText:string];
        NSLog(@"last name is %@", string);
        return;
    }
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    return;
}

我正在解析的XML文档如下所示:

<details>
<firstName>tester</firstName>
    <lastName>testingson</lastName>
    <address>
    <street1>123 Main St.</street1>
    <street2></street2>
    <city>Anywhere</city>
    <state>BC</state>
    <country></country>
    <postalCode>A0A0B0</postalCode>
</address>
<company>TEST</company>
<email>testing@test.com</email>
<cabbieNo>TEST</cabbieNo>
<driversLicense>TEST</driversLicense>
<plateNo>TEST</plateNo> 
<services>
    <taxi>1</taxi>
    <ladies>1</ladies>
    <limo>1</limo>
    <handicap>1</handicap>
</services>
</details>

奇怪的是,我的调试日志如下:

2012-10-01 15:36:35.742 myAPP[9974:c07] first name is tester
2012-10-01 15:36:35.743 myAPP[9974:c07] first name is
2012-10-01 15:36:35.743 myAPP[9974:c07] last name is testingson
2012-10-01 15:36:35.744 myAPP9974:c07] last name is 

正如你所看到的,它会两次查看每个元素,但是第二次,string为空(这不应该发生......实际上甚至不应该是第二个{{1}事件)。你们有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

你应该在didEndElement

中获得你的元素结果

这是示例

https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/XMLParsing/Articles/HandlingElements.html

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string

你应该附加字符串(找到的字符),例如:

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if (!currentStringValue) {
        // currentStringValue is an NSMutableString instance variable
        currentStringValue = [[NSMutableString alloc] initWithCapacity:50];
    }
    [currentStringValue appendString:string];
}

希望这会对你有所帮助。