Question

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;
Was it helpful?

Solution

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.

OTHER TIPS

XElement will always use InvariantCulture when converting to or from strings.
This is XML is meant to serialize data, and you don't want that to break when moving across cultures.

Parse() and ToString() use CurrentCulture by default.
This is because these functions are meant to be used when interacting with users, who expect to see numbers in their usual fashion.

You should always explicitly pass a culture when calling Parse() or ToString().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top