解析XML文件时无法跟踪错误源

时间:2011-06-02 11:47:14

标签: c# .net xml-serialization xml-deserialization

这是代码:

   var serializer = new DataContractSerializer(typeof(QuoteAndOfferCollection));
    try
    {
        using (var file = File.OpenRead(filename))
        {
            offers = (QuoteAndOfferCollection)serializer.ReadObject(file);
        }
    }
    catch (SerializationException sex)
    {
        File.AppendAllText(log, "Deserialization failed - " + sex);
        return;
    }

这是我得到的错误:

xmlDeserialization failed - System.Runtime.Serialization.SerializationException: There was an error deserializing the object of type Services.Dto2.QuoteAndOfferCollection. The value '' cannot be parsed as the type 'Int32'. ---> System.Xml.XmlException: The value '' cannot be parsed as the type 'Int32'. ---> System.FormatException: Input string was not in a correct format.
   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
   at System.Xml.XmlConvert.ToInt32(String s)
   at System.Xml.XmlConverter.ToInt32(String value)

我无法追踪''部分。

1 个答案:

答案 0 :(得分:0)

捕获异常并获取file.Position的值。这会让你知道文件在哪里有违规行。如果在FileStream周围包裹自定义流并跟踪读取的行数,则可以做得更好。

您也可以创建XmlReader,并将其传递给ReadObject。捕获异常时,请检查读者的属性。它可能会告诉您具有错误的行。

但是你需要移动异常被捕获的地方。也就是说,而不是:

try
{
    using (stream)
    {
        // deserialize
    }
}
catch
{
}

你想写:

using (stream)
{
    try
    {
        // deserialize
    }
    catch
    {
    }
}