Antoni Nicyfor Antoni Nicyfor - 1 month ago 7
C# Question

How to get element value and assign it to a Double using linq to xml?

I need to get the value of all 3 "avg" values from the following xml, and then assign them to a double array. using linq to xml. I'm brand new to linq to xml, so i'm not quite sure how to go about this.

Here is my current code

var q = from e in xDoc.Descendants("sell")
select new
{
result = e.Element("avg").Value
};


XML:

<?xml version='1.0' encoding='utf-8'?>
<evec_api version="2.0" method="marketstat_xml">
<marketstat>
<type id="626">
<buy>
<volume>11</volume>
<avg>9345454.55</avg>
<max>11500000.00</max>
<min>7500000.00</min>
<stddev>1862495.34</stddev>
<median>7600000.00</median>
<percentile>11500000.00</percentile>
</buy>
<sell>
<volume>23</volume>
<avg>18749987.25</avg>
<max>18749987.25</max>
<min>18749987.25</min>
<stddev>0.00</stddev>
<median>18749987.25</median>
<percentile>18749987.25</percentile>
</sell>
<all>
<volume>34</volume>
<avg>15707344.32</avg>
<max>18749987.25</max>
<min>7500000.00</min>
<stddev>4573474.77</stddev>
<median>18749987.25</median>
<percentile>7500000.00</percentile>
</all>
</type>
</marketstat>
</evec_api>

Answer

The problem with your code above is that you are retrieving only the value of one of the avgs. Using the Descendants you can find all the avgs and then get the value:

var result = xDoc.Descendants("avg").Select(e => (double)e);

If you want to be sure that it is a double and not fail on and InvalidCast then use double.TryParse:

double value = 0;
var result = (from element in xDoc.Descendants("avg")
              where double.TryParse(element.Value, out value)
              select value).ToList();

// result: 9345454.55, 18749987.25, 15707344.32

If you want the result to also have some assassination between the number and from where it came you can use the .Parent property:

double value = 0;
var result = (from element in xDoc.Descendants("avg")
              where  double.TryParse(element.Value, out value)
              select new
              {
                  Tag = element.Parent.Name.LocalName,
                  Value = value
              }).ToList();

enter image description here