Cocoa/Obj-C - Count elements in XML file
Got an application wich read some infos in a specific XML file. I would like to add one more option, here is the description:
Here is an example of my XML type file:
<?xml version="1.0" ?>
<Report>
<ReportCreationDate>20110307162840</ReportCreationDate>
<ReportTitle>Title sample</ReportTitle>
<ReportDescription>Description sample</ReportDescription>
<Videos>
<Video>
<VideoTitle>Video 1</VideoTitle>
<VideoDescription>Video description sample</VideoDescription>
</Video>
<Video>
<VideoTitle>Video 2</VideoTitle>
<VideoDescription>Video description sample</VideoDescription>
</Video>
</Videos>
</Report>
I would like to c开发者_如何学Pythonount how many <Video>
elements is there in the <Videos>
node.
How can I do that? Using NSXMLDocument?
I would like to write the result in a TextField.
Example: XML file contains 5 videos. If someone can help, it would be great! Thanks in advance Miskia (and sorry for my poor english, i'm a frenchy :p)Something like this should get the job done. I'll leave the error handling up to you.
NSData *data = [NSData dataWithContentsOfFile:pathToYourXMLFile];
NSError *error = nil;
NSXMLDocument *document = [[NSXMLDocument alloc] initWithData:data options:0 error:&error];
if(!error)
{
NSXMLElement *rootElement = [document rootElement];
NSUInteger count = [[rootElement nodesForXPath:@"//Video" error:&error] count];
if(!error)
{
NSString *videosCount = nil;
if(count == 0)
videosCount = [NSString stringWithFormat:@"XML file contains no videos."];
else if(count == 1)
videosCount = [NSString stringWithFormat:@"XML file contains 1 video."];
else
videosCount = [NSString stringWithFormat:@"XML file contains %d videos.", count];
[myTextField setStringValue:videosCount];
}
}
[document release]
精彩评论