0

I am trying to put the contents of an XML file into an NSMutableArray. I want to be able to get the following result:

NSLog(@"%@", [myarray objectAtIndex: 1];  will return cookie.

The xml file looks like this:

<row>
<Word>aardvark</Word>
</row>

<row>
<Word>cookie</Word>
</row>

This is the code I have so far:

-(void)checkdictionary {
    NSString *xmlPath = [[NSBundle mainBundle] pathForResource:@"englishwords" ofType:@"xml"];
    NSData *xmlData = [NSData dataWithContentsOfFile:xmlPath];
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:xmlData];
    [xmlParser setDelegate:self];
    [xmlParser parse];
}

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

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

        }
}

1 Answer 1

2

There are some delegate methods to implement when using NSXMLParser class.

If your purpose is to get all the word contained between the Word XML tag, you can do this way.

In your .h file create a BOOL named _isWordTag and a NSMutableArray names _words.

@interface MyClass
{
    BOOL _isWordTag;
    NSMutableArray _words;
}

Then, in the .m file set the BOOL named _isWordTag and the NSMutableArray named _words.

- (id)init
{
    ...
    _isWordTag = NO;
    _words = [NSMutableArray array];
    ...
}

To use NSXMLParer you have to implement some delegate from NSXMLParserDelegate protocol

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if ([elementName isEqualToString:@"Word"])
    {
        _isWordTag = YES;
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString:@"Word"])
    {
        _isWordTag = NO;
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{    
    if (_isWordTag)
    {
        [_words addObject:string];
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.