Mokmeuh
Mokmeuh

Reputation: 885

Load xml row into 2D array

So I have this xml

<document>
  <Month>
    <Depth>-0,25</Depth>
    <October>0,95</October>
    <November>-0,90</November>
    ...
  </Month>
  <Month>
    <Depth>-0,5</Depth>
    <October>0,47</October>
    <November>-0,17</November>
    ...
  </Month>
  ...
</document>

I've searched a bit and I saw some way to do it with linq but only with a 1D array, becasue what I would like to eventually end up with would be

Array[0,0] = -0.25
Array[0,1] = 0.95
Array[0,2] = -0.90
...

Upvotes: 0

Views: 361

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502536

If you're happy with a jagged array (an array of arrays) then LINQ makes it fairly easy:

XDocument doc = XDocument.Load(...);
var array = doc.Root
               .Elements("Month")
               .Select(month => month.Elements().Select(x => (double) x).ToArray())
               .ToArray();

If you need a rectangular array, that's trickier.

Personally I would actually build a custom type with Depth, October and November properties, rather than relying on the order of the elements within Month, but that's a different matter.

Note that the above cast to double will (probably?) fail for the values you've got there - more conventional XML would use . instead of ,. However, if it does fail you can use double.Parse(x.Value, someAppropriateCulture) instead.

Upvotes: 3

Related Questions