How can we can we handle self-closing Tags in NSXmlparser? There is no starting element and end element -- is it possible to handle the following type of Tags?
<ITEM NAME/>
<REG Number/>
Any XML Parser, including NSXMLParser, should be treating this:
<ITEMNAME/>
identically to this XML:
<ITEMNAME></ITEMNAME>
In other words, as far as the parser code you write is concerned, you should see both the start and the end of the element callbacks being invoked by the parser. To prove this out, I put the following sample XML in a file:
<top>
<sample1/>
<sample2 attr1="a"/>
</top>
I then implemented the following code to load this file and parse it:
NSURL *sampleURL = [[NSBundle mainBundle] URLForResource:@"sample" withExtension:@"xml"];
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:sampleURL];
[parser setDelegate:self];
[parser parse];
My parser delegate methods were implemented as follows:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI: (NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
NSLog(@"Received didStartElement callback for tag: %@", elementName);
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
NSLog(@"Received didEndElement callback for tag: %@", elementName);
}
When I ran this code I saw the following console output:
2012-01-01 22:24:24.011 SampleXML[10248:707] Received didStartElement callback for tag: top
2012-01-01 22:24:24.012 SampleXML[10248:707] Received didStartElement callback for tag: sample1
2012-01-01 22:24:24.013 SampleXML[10248:707] Received didEndElement callback for tag: sample1
2012-01-01 22:24:24.013 SampleXML[10248:707] Received didStartElement callback for tag: sample2
2012-01-01 22:24:24.015 SampleXML[10248:707] Received didEndElement callback for tag: sample2
2012-01-01 22:24:24.015 SampleXML[10248:707] Received didEndElement callback for tag: top
As you can see, I got both a didStartElement and didEndElement callback for both the sample1 and sample2 tags, which is how it should be working.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With