I get a System.FormatException thrown when i try to parse XML into an object. As far as I can tell, it's due to the culture used in System.Xml.Serialization.XmlSerializer.Deserialize, wich expects a dot as the decimal character, but the xml contains a comma.
The object looks as follows:
public sealed class Transaction
{
[XmlElement("transactionDate")]
public DateTime TransactionDate { get; set; }
[XmlElement("transactionAmount")]
public decimal Amount { get; set; }
[XmlElement("transactionDescription")]
public string Description { get; set; }
[XmlElement("transactionType")]
public int Type { get; set; }
public static Transaction FromXmlString(string xmlString)
{
var reader = new StringReader(xmlString);
var serializer = new XmlSerializer(typeof(Transaction));
var instance = (Transaction) serializer.Deserialize(reader);
return instance;
}
}
The xml:
<transaction>
<transactionDate> 2013-07-02 <transactionDate>
<transactionAmount>-459,00</transactionAmount>
<transactionDescription>description</transactionDescription>
<transactionType>1</transactionType>
</transaction>
I've made it work by introducing a second property that parses the first using my own culture:
namespace MyNamespace
{
[XmlRoot("transaction"), XmlType("Transaction")]
public sealed class Transaction
{
[XmlElement("transactionDate")]
public DateTime TransactionDate { get; set; }
[XmlElement("transactionAmount")]
public string Amount { get; set; }
public decimal AmountAsDecimal {
get
{
decimal value;
Decimal.TryParse(Amount, NumberStyles.Any, CultureInfo.CreateSpecificCulture("sv-SE"), out value);
return value;
}
}
[XmlElement("transactionDescription")]
public string Description { get; set; }
[XmlElement("transactionType")]
public int Type { get; set; }
public static Transaction FromXmlString(string xmlString)
{
var reader = new StringReader(xmlString);
var serializer = new XmlSerializer(typeof(Transaction));
var instance = (Transaction) serializer.Deserialize(reader);
return instance;
}
}
}
which exposes an extra property that i don't want there.
So my question is: is there another way to do this, without iterating over each element and parsing/assigning it to the object "manually"?
AmountAsDecimal
with[XmlIgnore]
just so it's a bit more obvious). Regardless, so long as your serialized objects are purely data-transfer objects and abstracted from your application/business logic, then it shouldn't hurt too much I hope. – Solidaritypublic decimal Amount
as the value that you would get/set normally in your code API but have it as[XmlIgnore]
. Then have apublic string SerializedAmount
property whose get/set implementations would format/parse your specialized culture. At least this way the API you use to write theTransaction
object doesn't have to think how to format the string; it just writes adecimal
value. If the way you write it (you change theSerializedAmount
property for example) then your code doesn't care. – Solidarity