I am having issues with XElement and Culture.
My local culture is French. Floating value are written with a comma instead of a point.
Console.WriteLine(1.1d);
//1,1
However when I put a double in an XElement, it is stored in american format.
XElement myXmlElement = new XElement("ADoubleElement", 1.1d);
Console.WriteLine(myXmlElement.Value);
//1.1
Therefore when I try to parse back the value of my XElement, I get a FormatException.
XElement myXmlElement = new XElement("ADoubleElement", 1.1d);
double myDouble = double.Parse(myXmlElement.Value);
//Throws a FormatException
I find this behaviour really strange. When I write a XDoucment, it is not written in the culture of the application or the thread but always in american culture. Am I missing something ? I have some workaround to behave the way I expect but I do not find them very "clean".
//This will work
XElement myXmlElement = new XElement("ADoubleElement", 1.1d.ToString());
double myDouble = double.Parse(myXmlElement.Value);
//This will also work but if I write XElement, it will not have the correct Culture
XElement myXmlElement = new XElement("ADoubleElement", 1.1d);
double myDouble = (double)myXmlElement;
XML specification describes how data should be formatted, and that's why XElement
does not use your culture - it follows XML specification (which is actually probably the same as InvariantCulture
)
That's also why casting XElement
to double
works and double.Parse
doesn't: it follows XML specification formats instead of local ones.