0

我必须读取 XML 文件并读取 XML 文件中的 id 属性,但字典为空。xml是:

 <?xml version='1.0' encoding='UTF-8'?>
 <root>
<event id="2"></event>
 </root>

我的代码:

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

  NSLog(@"elementName is %@", elementName);
  // elementName is root
  NSLog(@"AttributeDict is %@", attributeDict);
  //AttributeDict is { } why?
  //I must extract "id" in event but does not entry

if ([elementName isEqualToString:@"event"]){ 

    NSLog(@" %@", elementName);

}

}
4

1 回答 1

1

你需要这样做:

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict
{
    if ([elementName isEqualToString:@"event"])
    {
        NSLog(@" %@", [attributeDict objectForKey:@"id");
    }

}

该元素root没有任何属性,这就是为什么attributeDict显示为空,什么时候elementName是根。

于 2013-08-30T11:40:50.867 回答