3

I am making a text-based game in C++ and I want to load the objects (weapons, enemies..) from an XML file. I want to implement my own XML parser. My XML file looks like this:

<GameData>
    <weapon>
        <damage>90</damage>
        <name>Weapon Name</name>
        <type>sword</type>
    </weapon>
    ...
    ...
</GameData>

I have an idea of how to do this, pseudocode below:

while(getline file){
  if(object=weapon)
    new weapon object from values
    Skip to </weapon>
  else if(object=potion)
    new potion object from values
    Skip to </potion>
  //add else if for every other objects.
}

My problem with this is that I want my parser to work for a file with like 100 different objects so I'm trying to find a solution that does not involve chained if statements, but I am stuck...

Ideally I'd want to write a function that takes as input the object type as a string(read from XML file), and an array of strings for the values of the object, and that creates the appropriate object. I am not looking for a detailed solution, just something that could push me in the right direction.

Thank you!

  • What is the reason you want to avoid chained if statements? Is it for efficiency reasons or is it for readability purposes? – Empty Space May 14 '20 at 16:24
  • 3
    *I want to implement my own XML parser.* No, you really don't. Or, if you really do, you really shouldn't. *I am not looking for a detailed solution, just something that could push me in the right direction.* Here's an important push in the right direction: Use an XML parser. – kjhughes May 14 '20 at 17:08

0 Answers0