iOS中的xml解析显示为null

时间:2013-08-30 11:18:55

标签: ios xml xml-parsing

我必须读取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);

}

}

1 个答案:

答案 0 :(得分: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为root时elementName显示为空的原因。