Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 44897
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 10, 20262026-05-10T15:43:27+00:00 2026-05-10T15:43:27+00:00

I’m doing some Objective-C programming that involves parsing an NSXmlDocument and populating an objects

  • 0

I’m doing some Objective-C programming that involves parsing an NSXmlDocument and populating an objects properties from the result.

First version looked like this:

if([elementName compare:@'companyName'] == 0)    [character setCorporationName:currentElementText];  else if([elementName compare:@'corporationID'] == 0)    [character setCorporationID:currentElementText];  else if([elementName compare:@'name'] == 0)    ... 

But I don’t like the if-else-if-else pattern this produces. Looking at the switch statement I see that i can only handle ints, chars etc and not objects… so is there a better implementation pattern I’m not aware of?

BTW I did actually come up with a better solution for setting the object’s properties, but I want to know specifically about the if–else vs switch pattern in Objective-C

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-10T15:43:27+00:00Added an answer on May 10, 2026 at 3:43 pm

    I hope you’ll all forgive me for going out on a limb here, but I would like to address the more general question of parsing XML documents in Cocoa without the need of if-else statements. The question as originally stated assigns the current element text to an instance variable of the character object. As jmah pointed out, this can be solved using key-value coding. However, in a more complex XML document this might not be possible. Consider for example the following.

    <xmlroot>     <corporationID>         <stockSymbol>EXAM</stockSymbol>         <uuid>31337</uuid>     </corporationID>     <companyName>Example Inc.</companyName> </xmlroot> 

    There are multiple approaches to dealing with this. Off of the top of my head, I can think of two using NSXMLDocument. The first uses NSXMLElement. It is fairly straightforward and does not involve the if-else issue at all. You simply get the root element and go through its named elements one by one.

    NSXMLElement* root = [xmlDocument rootElement];  // Assuming that we only have one of each element. [character setCorperationName:[[[root elementsForName:@'companyName'] objectAtIndex:0] stringValue]];  NSXMLElement* corperationId = [root elementsForName:@'corporationID']; [character setCorperationStockSymbol:[[[corperationId elementsForName:@'stockSymbol'] objectAtIndex:0] stringValue]]; [character setCorperationUUID:[[[corperationId elementsForName:@'uuid'] objectAtIndex:0] stringValue]]; 

    The next one uses the more general NSXMLNode, walks through the tree, and directly uses the if-else structure.

    // The first line is the same as the last example, because NSXMLElement inherits from NSXMLNode NSXMLNode* aNode = [xmlDocument rootElement]; while(aNode = [aNode nextNode]){     if([[aNode name] isEqualToString:@'companyName']){         [character setCorperationName:[aNode stringValue]];     }else if([[aNode name] isEqualToString:@'corporationID']){         NSXMLNode* correctParent = aNode;         while((aNode = [aNode nextNode]) == nil && [aNode parent != correctParent){             if([[aNode name] isEqualToString:@'stockSymbol']){                 [character setCorperationStockSymbol:[aNode stringValue]];             }else if([[aNode name] isEqualToString:@'uuid']){                 [character setCorperationUUID:[aNode stringValue]];             }         }     } } 

    This is a good candidate for eliminating the if-else structure, but like the original problem, we can’t simply use switch-case here. However, we can still eliminate if-else by using performSelector. The first step is to define the a method for each element.

    - (NSNode*)parse_companyName:(NSNode*)aNode {     [character setCorperationName:[aNode stringValue]];     return aNode; }  - (NSNode*)parse_corporationID:(NSNode*)aNode {     NSXMLNode* correctParent = aNode;     while((aNode = [aNode nextNode]) == nil && [aNode parent != correctParent){         [self invokeMethodForNode:aNode prefix:@'parse_corporationID_'];     }     return [aNode previousNode]; }  - (NSNode*)parse_corporationID_stockSymbol:(NSNode*)aNode {     [character setCorperationStockSymbol:[aNode stringValue]];     return aNode; }  - (NSNode*)parse_corporationID_uuid:(NSNode*)aNode {     [character setCorperationUUID:[aNode stringValue]];     return aNode; } 

    The magic happens in the invokeMethodForNode:prefix: method. We generate the selector based on the name of the element, and perform that selector with aNode as the only parameter. Presto bango, we’ve eliminated the need for an if-else statement. Here’s the code for that method.

    - (NSNode*)invokeMethodForNode:(NSNode*)aNode prefix:(NSString*)aPrefix {     NSNode* ret = nil;     NSString* methodName = [NSString stringWithFormat:@'%@%@:', prefix, [aNode name]];     SEL selector = NSSelectorFromString(methodName);     if([self respondsToSelector:selector])         ret = [self performSelector:selector withObject:aNode];     return ret; } 

    Now, instead of our larger if-else statement (the one that differentiated between companyName and corporationID), we can simply write one line of code

    NSXMLNode* aNode = [xmlDocument rootElement]; while(aNode = [aNode nextNode]){     aNode = [self invokeMethodForNode:aNode prefix:@'parse_']; } 

    Now I apologize if I got any of this wrong, it’s been a while since I’ve written anything with NSXMLDocument, it’s late at night and I didn’t actually test this code. So if you see anything wrong, please leave a comment or edit this answer.

    However, I believe I have just shown how properly-named selectors can be used in Cocoa to completely eliminate if-else statements in cases like this. There are a few gotchas and corner cases. The performSelector: family of methods only takes 0, 1, or 2 argument methods whose arguments and return types are objects, so if the types of the arguments and return type are not objects, or if there are more than two arguments, then you would have to use an NSInvocation to invoke it. You have to make sure that the method names you generate aren’t going to call other methods, especially if the target of the call is another object, and this particular method naming scheme won’t work on elements with non-alphanumeric characters. You could get around that by escaping the XML element names in your method names somehow, or by building an NSDictionary using the method names as the keys and the selectors as the values. This can get pretty memory intensive and end up taking a longer time. performSelector dispatch like I described is pretty fast. For very large if-else statements, this method may even be faster than an if-else statement.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 101k
  • Answers 101k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer You mean redirect to page? document.location = 'http://yourpage'; May 11, 2026 at 8:02 pm
  • Editorial Team
    Editorial Team added an answer You have to use the CreateProcess() function to run the… May 11, 2026 at 8:02 pm
  • Editorial Team
    Editorial Team added an answer Found the answer in a MS KB article: File permissions… May 11, 2026 at 8:02 pm

Related Questions

I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
I am currently running into a problem where an element is coming back from
Seemingly simple, but I cannot find anything relevant on the web. What is the
Configuring TinyMCE to allow for tags, based on a customer requirement. My config is
Is it possible to replace javascript w/ HTML if JavaScript is not enabled on

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.