Double-value XML deserialization with German decimal separator in C #

I am 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); 

here's the Movie class for reference:

 [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(); } } 

as soon as I set <price> to 1.99 , it works fine. when I use the German German decimal separator 1,99 , it no longer works.

consult

+7
source share
3 answers

As already noted, this is simply an invalid way to represent a numeric value in XML. This is normal for a string. You can do:

 [XmlIgnore] public decimal Price {get;set;} [XmlElement("price")] public string PriceFormatted { get { return Price.ToString(...); } set { Price = decimal.Parse(value, ...); } } 

Where "..." represents your choice of format specifier and CultureInfo

+7
source

In the XML-Schema specification, double / decimal should be represented . , so this is design behavior.

You can replace the price type with a string, and then have an Realprice property that uses Double.TryParse with the corresponding CultureInfo or NumberFormatInfo .

 [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; } } 
+3
source

As already mentioned, XmlSerializer is not suitable for you because it will use the W3C schema type specification.

Alternative solutions include using an XSLT file to convert the input XML before deserializing or using another tool such as Linq to XML.

+1
source

All Articles