0

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
...
2
  • 1
    Do you have to have a double[,] or could it be a double[][]? (Also note that numbers in XML files are typically written using the invariant culture... it's odd to see a , as the decimal separator.) Commented Jan 31, 2014 at 20:56
  • In my point of view (since I'm not experiemented) it doesn't change anythings between both, but I have no requirement, but I will look to know the difference between both Commented Jan 31, 2014 at 20:57

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

9 Comments

Yes, I'm canadian, and we use ,. Is there any major difference betwen a jagged array and a rectangular one ?
+1. Need special feature on SO "Question already have answer with 600K+ reputation" so others can safely ignore it :)
@Mokmeuh: You may be Canadian, but XML typically tries to avoid being culture-specific. If you write your data in a standardized way, it'll be easier for others to read it. There are various differences between jagged and rectangular arrays - see msdn.microsoft.com/en-us/library/2s05feca.aspx and msdn.microsoft.com/en-us/library/2yd9wwz4.aspx
Thank you alot, you have been really helpfull.
I've just noticed, maybe I've been not clair, sorry if it's the case, but with what you gave me, what's inside the month tag is a column, when I converted them from the excel file I,ve put them as a row, so how can I invert what you did :/ ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.