grabthefish
grabthefish

Reputation: 918

Read integer from XML with LINQ

I got this xml file from where i want to get the amount of money from

<data>
  <money>300</money>
  <lives>10</lives>
  <start>
    <x>10</x>
    <y>-1</y>
    <direction>down</direction>
  </start>
  <waves>
    <wave>
      <slimes>5</slimes>
      <healthPerSlime>60</healthPerSlime>
      <money>25</money>
    </wave>
    <wave>
      <slimes>10</slimes>
      <healthPerSlime>80</healthPerSlime>
      <money>30</money>
    </wave>
  </waves>
</data>

i tried it in 2 ways:

money = int.Parse(xmlDoc.Elements().Select(x => x.Element("money").Value).ToString());

and:

money = int.Parse((from element in xmlDoc.Descendants("money")
                              select element.Value).ToString());

but i keep getting a FormatException "Input string was not in a correct format."

can someone tell me what im doing wrong.

Upvotes: 0

Views: 4328

Answers (3)

Jordan Davidson
Jordan Davidson

Reputation: 419

everyone seems to be giving you an answer using functions so I'll give one using the linq syntax

int money = 
    from element in xmlDoc.Root
    where element.Name == "money"
    select int.Parse(element.Value)).First();

so lets break it down.

xmlDoc.Root brings you to <data> then you search all of the elements at the next level and return all of them where .Name == "money" and then you select the .Value of those and parse them into an int. This returns a list of items so you just grab the .First() one and return it to money.

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236268

Just cast money element to integer. XElements supports explicit casting to string, boolean, integer and some other types. E.g. if you want value of data element money:

money = (int)xmlDoc.Root.Element("money"); // 300

Parsing of wave's money will look like:

var data = xmlDoc.Root;
int money = (int)data.Element("money"); // 300
int lives = (int)data.Element("lives"); // 10
var waves = from w in data.Element("waves").Elements()
            select new {
               Slimes = (int)w.Element("slimes"),
               HealthPerSlime = (int)w.Element("healthPerSlime"),
               Money = (int)w.Element("money")
            };

That will return collection of two anonymous 'wave' objects (consider to create class for this data) with slimes, healthPerSlime and money parsed as integers.

Upvotes: 1

Anirudha
Anirudha

Reputation: 32807

It should be

xmlDoc.Elements()
      .Select(x => int.Parse(x.Element("money").Value))
      .Sum();

Upvotes: 3

Related Questions