获取正确的输出:NSXML Parser

时间:2012-06-04 20:57:37

标签: iphone objective-c ios xcode ipad

我的XML文件是:

<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0">
    <count count="3" />
    <spac>
        <opt>aa</opt>
        <opt>bb</opt>
    </spac>
</plist>

我已经为NSXML parssr使用了以下代码行:

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 
 namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName 
attributes:(NSDictionary *)attributeDict {

if([elementName isEqualToString:@"spaces"]) {
    //Initialize the array.
    appDelegate.api = [[NSMutableArray alloc] init];

}

}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { 
[appDelegate.api addObject:string];
    NSLog(@"the count is :%d", [appDelegate.api count]);
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName 
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if([elementName isEqualToString:@"spaces"])
    return;
}

但我在gdb上得到以下输出,我无法弄清楚原因:

2012-06-05 02:20:57.940 XML[490:f803] the count is :0
2012-06-05 02:20:57.942 XML[490:f803] the count is :0
2012-06-05 02:20:57.943 XML[490:f803] the count is :1
2012-06-05 02:20:57.944 XML[490:f803] the count is :2
2012-06-05 02:20:57.945 XML[490:f803] the count is :3
2012-06-05 02:20:57.946 XML[490:f803] the count is :4
2012-06-05 02:20:57.946 XML[490:f803] the count is :5
2012-06-05 02:20:57.948 XML[490:f803] the count is :6
2012-06-05 02:20:57.948 XML[490:f803] the count is :7
2012-06-05 02:20:57.949 XML[490:f803] the count is :8

有人可以帮帮我吗?我是客观C的新手。谢谢。

1 个答案:

答案 0 :(得分:0)

你打印出两个零的原因是因为在你的第一个回调中你只在元素为spaces时创建一个新的可变数组。

if([elementName isEqualToString:@"spaces"]) { //<- check for spaces to create array
    //Initialize the array.
    appDelegate.api = [[NSMutableArray alloc] init];

}

但是,为找到字符的每个元素调用- (void)parser:foundCharacters:。因此,找到的第一个节点将添加到nil数组并打印0.在spaces之后找到的任何节点将继续添加不需要的字符。如果您的XML看起来如下所示,您可以看到发生了什么。

<xml>
   <node1>text that is found but gets added to a nil array (prints 0 count)</node1>
   <node2>more text that is found but gets added to a nil array (prints 0 count)</node2>
   <spaces>this is the spaces text that will get added to the array correctly</spaces>
   <node4>this text will be added to the non-nil array and appear to be spaces</node4>
</xml>