C# C语言中带德语小数分隔符的双值XML反序列化
我正在尝试从德语xml字符串反序列化电影对象:C# C语言中带德语小数分隔符的双值XML反序列化,c#,xml,serialization,localization,xml-deserialization,C#,Xml,Serialization,Localization,Xml Deserialization,我正在尝试从德语xml字符串反序列化电影对象: string inputString = "<?xml version=\"1.0\"?>" + "<movie title=\"Great Bollywood Stuff\">" + "<rating>5</rating>" + "<price>1,99</price>" // <-- Price with German decimal sepa
string inputString = "<?xml version=\"1.0\"?>"
+ "<movie title=\"Great Bollywood Stuff\">"
+ "<rating>5</rating>"
+ "<price>1,99</price>" // <-- Price with German decimal separator!
+ "</movie>";
XmlSerializer movieSerializer = new XmlSerializer(typeof(Movie));
Movie inputMovie;
using (StringReader sr = new StringReader(inputString))
{
inputMovie = (Movie)movieSerializer.Deserialize(sr);
}
System.Console.WriteLine(inputMovie);
只要我把a的值设为1.99,它就工作得很好。当我使用德语小数点分隔符1,99时,它不再工作了
请注意如前所述,XmlSerializer不是适合您的工具,因为它将使用W3C模式数据类型规范
替代解决方案包括在反序列化之前使用XSLT文件转换输入XML,或者使用另一种工具(如Linq to XML)。如前所述,这根本不是用XML表示数值的有效方法。不过,这对一根绳子来说很好。你可以做:
[XmlIgnore]
public decimal Price {get;set;}
[XmlElement("price")]
public string PriceFormatted {
get { return Price.ToString(...); }
set { Price = decimal.Parse(value, ...); }
}
在哪里。。。表示您对格式说明符的选择,XML模式规范a中的CultureInfo需要用表示。所以这种行为是故意的
您可以将Price的类型替换为string,然后使用一个非序列化的属性Realprice,该属性使用带有适当CultureInfo或NumberFormatInfo的Double.TryParse
您是否有关联的模式?在XML模式规范中,需要用,所以这种行为是故意的。您可以将Price的类型替换为string,然后使用一个非序列化的属性Realprice,该属性使用Double.Parse和一个适当的格式stringxml以这种格式提供给我,我对此无能为力。但是谢谢你的回答!重要提示:货币值应该几乎总是十进制的,而不是双精度的。在我的例子中,CultureInfo.getcultureinfo-DE.numberformat您能给出一个示例吗?我可以给你一些翻译的想法
[XmlIgnore]
public decimal Price {get;set;}
[XmlElement("price")]
public string PriceFormatted {
get { return Price.ToString(...); }
set { Price = decimal.Parse(value, ...); }
}
[XmlRoot("movie")]
public class Movie {
[XmlElement("price")]
public string Price { get; set; }
[XmlIgnore]
public double RealPrice {
get {
double resultprice;
if (!Double.TryParse(
Price,
NumberStyles.Any,
new CultureInfo("de-DE"),
resultprice)) throw new ArgumentException("price");
// resultprice is now parsed, if not an exception is thrown
return resultprice;
}
}