Very good question that raises many crucial conceptual issues... I'll
try to be as verbose as possible.
1. Serialization/Deserialization is distinct from the process of
parsing a string into another datatype and the reverse process
(calling ToString() on the type).
2. Culture info can never be specified as part of an XML file, because
XML by definition contains data. Data is never (or atleast should
never be) culture sensitive. An XML file can only specify encoding for
the data contained within.
3. You can specify a Culture when serializing the object into XML by
using a StringWriter as backing, and specifying the culture in the
StringWriter constructor. However, it will not have any effect on the
Serialized XML because the XmlSerializer class in the .NET framework
conforms to the W3C spec in the manner that it internally uses the
XmlConvert class which always converts datatypes to the Invariant
culture.
Let's take for example the following code:
---
[Serializable]
public class Transaction
{
private double amt = 0;
private DateTime txnDate;
public double Amount
{
get { return amt; }
set { amt = value; }
}
public DateTime TransactionDate
{
get { return txnDate; }
set { txnDate = value; }
}
}
class Program
{
static void Main(string[] args)
{
// Set culture to Spanish.
Thread.CurrentThread.CurrentCulture = new CultureInfo("es-ES");
string serializedText;
Transaction txn = new Transaction();
txn.Amount = 123.456D;
txn.TransactionDate = new DateTime(2009, 07, 09);
XmlSerializer xsz = new XmlSerializer(typeof(Transaction));
using (StringWriter sw = new StringWriter
(CultureInfo.CurrentCulture))
{
xsz.Serialize(new XmlTextWriter(sw), txn);
serializedText = sw.ToString();
}
Console.WriteLine(serializedText);
}
}
---
What do you expect will be the output of the above Console app ? It
is :
---
<?xml version="1.0" encoding="utf-16"?>
<Transaction xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="
http://www.w3.org/2001/XMLSchema">
<Amount>123.456</Amount>
<TransactionDate>2009-10-15T00:00:00</TransactionDate>
</Transaction>
---
The point to note here is that the serialized XML contains both dates
and numbers in Invariant format, rather than the set culture. (In
Spanish, the number would be written as 123,456 and the date would be
in dd/mm/yyyy format, assuming Short date formats.)
You may ask why I am talking about Serialization when your question is
about the reverse process. The answer is that same rules apply to
objects. **Culture formatting should ONLY apply when the value is to
be extracted from an object and displayed to the user on the UI.**
Therefore, the answer to your question is that there is no way (and no
need) to specify culture information when serializing or deserializing
an object.