C#中使用德语十进制分隔符对双值进行XML反序列化 [英] XML-Deserialization of double value with German decimal separator in C#
本文介绍了C#中使用德语十进制分隔符对双值进行XML反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从德语" xml字符串反序列化Movie
对象:
i'm trying to deserialize a Movie
object from a "German" xml string:
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);
此处是Movie
类以供参考:
[XmlRoot("movie")]
public class Movie
{
[XmlAttribute("title")]
public string Title { get; set; }
[XmlElement("rating")]
public int Rating { get; set; }
[XmlElement("price")]
public double Price { get; set; }
public Movie()
{
}
public Movie(string title, int rating, double price)
{
this.Title = title;
this.Rating = rating;
this.Price = price;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder("Movie ");
sb.Append("[Title=").Append(this.Title);
sb.Append(", Rating=").Append(this.Rating);
sb.Append(", Price=").Append(this.Price);
sb.Append("]");
return sb.ToString();
}
}
只要我把<price>
作为1.99
,它就可以完美地工作.当我使用德语德语小数分隔符1,99
时,它不再起作用.
as long i put a the <price>
as 1.99
it works perfectly. when i use the German German decimal separator 1,99
it's not working anymore.
请咨询
推荐答案
如前所述,这根本不是表示XML中数字值的有效方法.不过,对于字符串来说是很好的.您可以这样做:
As already noted, that simply isn't a valid way of representing a numeric value in XML. It is fine for a string though. You could do:
[XmlIgnore]
public decimal Price {get;set;}
[XmlElement("price")]
public string PriceFormatted {
get { return Price.ToString(...); }
set { Price = decimal.Parse(value, ...); }
}
其中"..."代表您选择的格式说明符和CultureInfo
Where "..." represents your choice of format specifier and CultureInfo
这篇关于C#中使用德语十进制分隔符对双值进行XML反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文