I have problem with building object holding XML data using Linq. For example, I have XML data in url http://api.eve-central.com/api/marketstat?typeid=34&usesystem=30000142 . In MarketStat
class I want to hold type id
value and in MarketValue
class array I want to hold volume
avg
max
min
stddev
median
percentile
values of buy
sell
all
nodes. I have never used linq so far so please help me fix my problem in code below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace ConsoleApplication1
{
internal class MarketValue
{
public int Volume { get; set; }
public double Avg { get; set; }
public double Max { get; set; }
public double Min { get; set; }
public double Stddev { get; set; }
public double Median { get; set; }
public double Percentile { get; set; }
}
internal class MarketStat
{
public string Name { get; set; }
public MarketValue[] MarketValueses { get; set; }
}
internal class Program
{
private static List<MarketStat> list;
internal static void Main(string[] args)
{
list = (
from e in XDocument.Load("http://api.eve-central.com/api/marketstat?typeid=34&usesystem=30000142").
Root.Elements("marketstat")
select new MarketStat
{
Name = (string) e.Element("type id"),
MarketValueses = (
from mv in e.Elements("buy")
select new MarketValue
{
Volume = (int) mv.Element("volume"),
Avg = (double) mv.Element("avg"),
Max = (double)mv.Element("max"),
Min = (double)mv.Element("min"),
Stddev = (double)mv.Element("stddev"),
Median = (double)mv.Element("median"),
Percentile = (double)mv.Element("percentile")
}).ToArray()
}).ToList();
}
}
}
You're looking for an element called "type id". That's not a valid name for an element in XML. You should just look for elements called type
... that's the name of this element:
<type id="34">
If you want to filter by ID, you could then fetch the attribute id
.
You're also trying to fetch the buy
element directly from the marketstat
element - it isn't there; it's within the type
element. You need to pay more attention to the structure of the XML, basically.
My guess is that you should only expect a single buy
element, too - which makes things simpler. I suspect you don't need an array within each element of your results...
See more on this question at Stackoverflow