XmlSerializer to deserialize decimal with comma(,) decimal symbol

纵然是瞬间 提交于 2019-12-10 17:26:36

问题


I'd like to know if there is any simple way to deserialize decimal with comma decimal separator using XmlSerialier? I'am getting exported data in xml format from other software and all numbers(price, quantity, discount and many many more) in xml file has comma as decimal separator.

Here is simplified example what I have tried to do:

Lets say there is Product class with Name and Price:

[Serializable]
public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}

and I have xml...

string xmlExample = "<Product><Name>Coca Cola, 2L</Name><Price>3,50</Price></Product>";

when I'am trying to deserialize that xml...

XmlSerializer serializer = new XmlSerializer(typeof(Product));
StringReader stringReader = new StringReader(xmlExample);
Product product = serializer.Deserialize(stringReader) as Product; //<-- Error here

I'am getting error There is an error in XML document (1, 57).

Everythig works fine, when Price in xml is 3.50.

I know i could change Price propertie to sting and TryParse decimal, but maybe there is better solution (for example switch culture)?

Any suggestions, solutions and comments are appreciated.

UPDATE: Forgot to mention that my current culture settings already using comma as decimal symbol.


回答1:


I doubt there is a built-in way because XML documents with numbers that don't use period are not XML documents :) OTOH, this answer has quite a few possible solutions:

Summing numbers with comma as decimal separator in XSLT?



来源:https://stackoverflow.com/questions/6116354/xmlserializer-to-deserialize-decimal-with-comma-decimal-symbol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!