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

本文关键字:跟踪 错误 XML 文件 分析 | 更新日期: 2023-09-27 17:58:09

这是代码:

   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)

我无法跟踪"部分。

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

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

您还可以创建一个XmlReader,并将其传递给ReadObject。当您捕捉到异常时,请检查读取器的属性。它可能会告诉你错误的确切线路。

但您需要移动到捕捉到异常的位置。也就是说,而不是:

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

你想写:

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