无法使用NSXMLParser检索xml值

时间:2012-09-18 06:52:31

标签: php iphone objective-c cocoa-touch xml-parsing

我在xml中的php响应属于这种类型

<users>
<username>myemail</username>
<password>mypass</password>
 </users>

现在这是我的parseUrl类

  NSURL *parserUrl = [[[NSURL alloc] initWithString:urlString] autorelease];
        NSXMLParser *parser = [[[NSXMLParser alloc] initWithContentsOfURL:parserUrl] autorelease];
        [parser setDelegate:self];



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



    if ( [elementName isEqualToString:@"users"]) 
    {
        return;
    }



    if ( [elementName isEqualToString:@"username"] ) 
    {
        NSString *val = [attributeDict  objectForKey:@"username"] ;    
      return;
    }

}

现在的问题是,attributeDict给出了0对。该函数正在读取username, password and users,这意味着它可以进入此循环

   if ( [elementName isEqualToString:@"username"] ) 
        {
            NSString *val = [attributeDict  objectForKey:@"username"] ;    
          return;
        }

但我如何检索此节点的值?

2 个答案:

答案 0 :(得分:1)

删除return声明

和attributeDict总是包含属性。

e.g。

这里'id'是用户的属性。

获取字符串值,需要编写

//take string variable in header file 'elementname'

NSString *elementname;

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

elementname = elementName;
}

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

    elementname = elementName;
}


-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{

   if([elementname isEqualToString:@"username"])
   {
       NSLog(@"username : %@",string);
   }
   else if([elementname isEqualToString:@"password"])
   {
       NSLog(@"password : %@",string);
   }
}

答案 1 :(得分:0)

试试这个

-(void) parserDidStartDocument:(NSXMLParser *)parser
{
    list = [[NSMutableArray alloc] init];
    resultArray = [[NSMutableArray alloc] init];
    currentElementValue = [[NSMutableString alloc] init];
}
-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
{
currentElementName = [elementName copy];

if([elementName isEqualToString:@"username"])
{
    list = [[NSMutableArray alloc] init];
}
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName 
{
if([elementName isEqualToString:@"username"])
{
    [resultArray addObject: currentElementValue];
}
}

-(void) parserDidEndDocument:(NSXMLParser *)parser
{
NSLog(@"Result Array= %@",resultArray);
NSLog(@"list Array= %@",list);
}