0

我的 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 的新手。谢谢。

4

1 回答 1

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>
于 2012-06-04T21:30:40.447 回答