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

誰かが私を助けてくれますか?私はObjectiveCを初めて使用します。ありがとうございます。

4

1 に答える 1

0

ゼロが 2 つ出力される理由は、最初のコールバックで、要素が の場合にのみ新しい可変配列を作成するためです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 に答える