siddle siddle - 7 months ago 76
Objective-C Question

XML file parsing issue in IOS

I have a xml file which I'm adding to my project locally. I have got its path and easily visible in my console when loading a view. But when I start parsing and try to get the value from the first tag it is showing nothing when I NSLog the value.

My xml file is this,

<?xml version="1.0" encoding="UTF-8"?>
<QF id="AB2001" topic="Alertness" category="C&amp;M" ni_exempt="no">
<question>
<xref>DES s4, DES s9, HC r159-161</xref>
<text>Before you make a U-turn in the road, you should</text>
<graphic></graphic>
<prompt>Mark one answer</prompt>
<voice id="AB2001-1"/>

<explanation>
<text>If you want to make a U-turn, slow down and ensure that the road is clear in both directions. Make sure that the road is wide enough to carry out the manoeuvre safely.</text>
<voice id="AB2001-2"/>
</explanation>

</question>
<answers>
<answer correct="no">
<text>give an arm signal as well as using your indicators</text>
<graphic></graphic>
</answer>
<answer correct="no">
<text>signal so that other drivers can slow down for you</text>
<graphic></graphic>
</answer>
<answer correct="yes">
<text>look over your shoulder for a final check</text>
<graphic></graphic>
</answer>
<answer correct="no">
<text>select a higher gear than normal</text>
<graphic></graphic>
</answer>
</answers>




This is the delegate methods which I use to parse and NSLog the value to check whether it is coming or not.

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if([_currentElement isEqualToString:@"QF"]) {
NSLog(@"YY%@",[attributeDict objectForKey:@"id"]);
NSLog(@"Hi");
}
}

Answer Source

First use below code to start parsing of xml file:

NSData *data=[NSData dataWithContentsOfFile:pathOfFile];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];

xmlParser.delegate = self;
[xmlParser parse];

Also in header file of your class conforms to NSxmlparser protocol as follows:

  @interface ViewController : UIViewController<NSXMLParserDelegate>

then Use Following method:

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName

   attributes: (NSDictionary *)attributeDict
{
    if([elementName isEqualToString:@"QF"]) {
        NSLog(@"YY%@",[attributeDict objectForKey:@"id"]);
        NSLog(@"Hi");
    }

}

I have tried it with your file and it is working fine with my code and giving output on console as:

YYAB2001

2017-11-24 17:54:49.048539+0530 xmlParser[6718:394724] Hi

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download