Parsing NSXMLNode Attributes in Cocoa

后端 未结 2 1718
名媛妹妹
名媛妹妹 2021-02-08 05:31

Given the following XML file:

    

 

        
2条回答
  •  野的像风
    2021-02-08 05:59

    There are two options. If you continue to use NSXMLDocment and you have an NSXMLNode * for the a movie element, you can do this:

    if ([movieNode kind] == NSXMLElementKind)
    {
        NSXMLElement *movieElement = (NSXMLElement *) movieNode;
        NSArray *attributes = [movieElement attributes];
    
        for (NSXMLNode *attribute in attributes)
        {
            NSLog (@"%@ = %@", [attribute name], [attribute stringValue]);
        }
    }
    

    Otherwise, you can switch to using an NSXMLParser instead. This is an event driven parser that informs a delegate when it has parsed elements (among other things). The method you're after is parser:didStartElement:namespaceURI:qualifiedName:attributes:

    - (void) loadXMLFile
    {
        NSXMLParser *parser = [NSXMLParser parserWithContentsOfURL:@"file:///Users/jkem/test.xml"];
        [parser setDelegate:self];
        [parser parse];
    }
    
    
    // ... later ...
    
    -      (void)         parser:(NSXMLParser *)parser
                 didStartElement:(NSString *)elementName
                    namespaceURI:(NSString *)namespaceURI
                   qualifiedName:(NSString *)qualifiedName
                      attributes:(NSDictionary *)attributeDict
    {
        if ([elementName isEqualToString:@"movie"])
        {
            NSLog (@"%@", [attributeDict objectForKey:@"a"]);
            NSLog (@"%d", [[attributeDict objectForKey:@"b"] intValue]);
        }
    }
    

提交回复
热议问题