Search code examples
c#xmlparsingxmldocument

Is it possible to have non reapating element in an xml file?


I m working on a simple adventure game and right now I have an xml file to load the world and another for the player.

here is the simplified xml I'd like to create:

<root>
   <world>
        <location>
           //room 1
             <inventory>
                  talble, chair...
             </inventory>
        </location> 
        <location>
             //room 2
        </location>
   </world>
   <player>
       //some player stats i.e the location he is currently in.
       <inventory>
           the player bag containing objects
       </inventory>
   </player>
</root>

Will I be able to parse that file to get the player inventory or a location inventory? is it allowed to create that asymetrical xml or does it always have to be only repeating element?

Right now the game works but I am not sure it's good practice to separate those too files since I must always update theim at the same time. I'd rather merge those together.

Thanks a lot for the help. Mike


Solution

  • XDocument provides methods to access specific elements via a "path".

    To get all elements of the player's inventory, you would need code similar to this:

    IEnumerable<XElement> playerItems = x.Element("player").Element("inventory").Elements();
    

    And to get the objects of the first location:

    IEnumerable<XElement> locationObjects = x.Element("world").Elements("location").First().Element("inventory").Elements();
    

    Note the difference between Element() and Elements(), the first returns only one element; the second returns an IEnumerable<XElement>. This is important when you want to retrieve the objects of all locations.

    After you have retrieved all elements, you would need to process them; you can access the value of an element by the Value property which is a String.