Miguel
Miguel

Reputation: 79

Parsing through an XML file using a randomly generated integer

This has absolutely stumped me. I have an XML file which is basically a list of items that my program will be using in the game, each item has an associated ID such as

<Items>
<Item ID ="1">
  <Name>Food</Name>
  <Price>1 copper</Price>
 </Item>
</Items>

How can I write my code so that I can parse through the XML using that random integer? Once I find the correct ID for that integer then I will get the elements from the XML file and my game will then use them.

Thanks for any help you can give.

Upvotes: 1

Views: 117

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236268

With Linq to Xml you can select item element which have ID attribute equal value to your integer id variable:

var xdoc = XDocument.Load(fileName);
var item= xdoc.Descendants("Item")
              .FirstOrDefault(i => (int)i.Attribute("ID") == id);

Now if element with specified ID exists (i.e. item not null) you can write all it's elements value to Dictionary<string, string> with element name as key and element value as value:

if (item != null)   
{
    settings = item.Elements()
                   .ToDictionary(e => e.Name.LocalName, e => (string)e);   
}

Usage of settings dictionary:

if (settings.ContainsKey("Name"))
    name = settings["Name"]; // if id == 1 then name will be "Food"

Upvotes: 1

Related Questions