我必须读取一个XML文件并读取XML文件中的id属性,但是字典中的内容为null。 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);

}

}

最佳答案

您需要这样做:

- (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为root时elementName显示为空的原因。

10-08 03:08