我正在尝试从“德语” xml字符串反序列化Movie
对象:
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
时,它不再起作用。请指教
最佳答案
如前所述,这根本不是用XML表示数字值的有效方法。不过,对于字符串来说是很好的。您可以这样做:
[XmlIgnore]
public decimal Price {get;set;}
[XmlElement("price")]
public string PriceFormatted {
get { return Price.ToString(...); }
set { Price = decimal.Parse(value, ...); }
}
其中“...”代表您对格式说明符和CultureInfo的选择
关于c# - C#中使用德语十进制分隔符对双值进行XML反序列化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8463733/