我正在尝试将DataSet转换为XML,然后以文化不变的方式将其读回。起初这似乎很容易,因为默认情况下DataSet会使用不变文化。
对于我的第一次测试,我切换到法语区域设置并验证DataSet的WriteXml方法使用了双精度的不变文化设置。到目前为止,非常好。
对于第二次测试,我使用“区域和语言”下的“自定义格式”对话框将小数点符号更改为'#'和负号符号到'〜'。令我惊讶的是,这打破了我的单元测试。 XML仍然使用不变设置编写,但是当我尝试读取相同的XML时,我得到一个System.Format异常,说输入字符串的格式不正确。根据堆栈跟踪,ReadXml方法试图将值解析为Int32,即使我明确地将列的类型设置为Double!将小数符号和负号符号更改回法语默认值可修复问题。
我的测试代码如下所示。
[TestMethod]
public void TestDataSetSerialization()
{
// Verify that the locale settings are being picked up.
double testValue = -3.1;
string expectedInvariantText = "-3.1";
string expectedLocaleText = "~3#1";
string actualLocaleText = testValue.ToString();
Assert.AreEqual(expectedLocaleText, actualLocaleText);
double actualLocaleValue = Double.Parse(expectedLocaleText);
Assert.AreEqual(testValue, actualLocaleValue);
double actualInvariantValue = Double.Parse(expectedInvariantText, System.Globalization.CultureInfo.InvariantCulture);
Assert.AreEqual(testValue, actualInvariantValue);
// Check the data set's WriteXml and ReadXml methods.
DataSet dataSet = new DataSet();
dataSet.Locale = System.Globalization.CultureInfo.InvariantCulture;
DataTable dataTable = new DataTable();
const string columnName = "Double Values";
DataColumn dc = new DataColumn(columnName, typeof(double));
dataTable.Columns.Add(dc);
double[] doubleList = new double[] { 0.0, -1.1, 1.2 };
foreach (object doubleValue in doubleList)
{
DataRow dataRow = dataTable.NewRow();
dataRow[columnName] = doubleValue;
dataTable.Rows.Add(dataRow);
}
dataSet.Tables.Add(dataTable);
StringBuilder dataSetXml = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(dataSetXml))
{
dataSet.WriteXml(writer, XmlWriteMode.WriteSchema);
}
StringReader reader = new StringReader(dataSetXml.ToString());
DataSet readDataSet = new DataSet();
readDataSet.Locale = System.Globalization.CultureInfo.InvariantCulture;
// This throws a number format exception on a call to ParseInt32.
readDataSet.ReadXml(reader, XmlReadMode.ReadSchema);
}