简体   繁体   English

C#-XElement与文化

[英]C# - XElement and Culture

I am having issues with XElement and Culture. 我在XElement和文化方面遇到问题。

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中放入一个double时,它以美式格式存储。

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的值时,会收到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. 当我编写XDoucment时,它不是以应用程序或线程的文化来编写的,而是总是以美国文化来编写的。 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 ) XML规范描述了数据应如何格式化,这就是XElement不使用您的区域性的原因-它遵循XML规范(实际上可能与InvariantCulture相同)

That's also why casting XElement to double works and double.Parse doesn't: it follows XML specification formats instead of local ones. 这也是为什么将XElement强制转换为doubledouble原因double.Parse不能:它遵循XML规范格式而不是本地规范格式。

XElement will always use InvariantCulture when converting to or from strings. 在转换为字符串或从字符串转换时, XElement将始终使用InvariantCulture
This is XML is meant to serialize data, and you don't want that to break when moving across cultures. XML是用于序列化数据的,在跨文化迁移时,您不希望它中断。

Parse() and ToString() use CurrentCulture by default. 默认情况下, Parse()ToString()使用CurrentCulture
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() . 调用Parse()ToString()时,应始终明确传递一种区域性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM