1

I have an XML file of the following structure:

<xmlDocument version="1">
<subject id="1">
<maths marks="65"/>
<science marks="80"/>
<tamil marks="90"/>
<social marks="79"/>
<English marks="70"/>
</subject>
</xmlDocument>

How to parse and get this data using Objective C?

2 Answers 2

1
  1. Create an instance of NSXMLParser and assign a delegate to the parser.
  2. In your delegate class, implement the relevant methods of the NSXMLParserDelegate protocol.
  3. Call the parser's parse method.
  4. Ask more specific questions if you encounter problems.
Sign up to request clarification or add additional context in comments.

Comments

0

Since you don't have any text inside your tags you can use the parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName attributes:(NSDictionary *)attributeDict method on your delegate. Than you can store the values inside a dictionary or object. If you have multiple subject tags you can use the parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName to change the context of your parser. The official documentation should give you more details on which methods are available.

You could do something like that (incomplete implementation):

/*
 * Incomplete implementation just to give some pointers
 */
@implementation MyDelegate
    -(void) init {
        if((self = [super init])) {
            _subjects = [NSMutableArray new];
        }
    }
    -(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName attributes:(NSDictionary *)attributeDict {
        if([elementName equalsIgnoreCase:@"subject"]) {
            _context = [NSMutableDictionary new];
        } else {
            [_context setObject:[attributeDict valueForKey:@"mark"] forKey:elementName];
        }
    }
    - (void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName {
        [_subjects addObject:_context]
        [_context release]; _context = nil;
    }
@end

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.