C# how can I debug a deserialization exception?

喜夏-厌秋 提交于 2019-12-02 05:51:32

问题


I havve created a C# class representing an XSD using the XSD.exe tool. I use a valdiation code to check the consistency of the XML with the XSD. I got this working, but using another XML file causes exceptions.

The XML files are produced by an external program and I do not have access to the original code or to a published XSD.

During reading the XML during Deserialization I get an exception:

enter System.InvalidOperationException was unhandled

HResult=-2146233079 Message=Het XML-document (235, 17) contains an error.

The error is described as an attempt to convertt a string to a DateTime format (which cannt be a correct description).

I thougth (235,17) migt represent the location in the document, but this is not consistent with the call stack.

My question: can you help me with a good debugging strategy for this type of problems? I would like to know exactly at which line in the XML the exception occurs, but don't know how to do this.


回答1:


Line and character numbers are reported to the exception message via the IXmlLineInfo interface, which XmlTextReader implements. Of note, both the line number and line position start with number one (and are zero only when not available).

Thus "(235, 17)" are the line number and position in the line (starting at one) at which the reader was positioned when the error was thrown. In most cases, that will be actual position in the XML file at which the error occurs. However, sometimes the XML Serializer will have advanced the reader to the next node before the error is thrown. From experimentation:

  1. If the XML is not well-formed, then the error will be where the line and position report.

  2. If the XML is well formed but an attribute value cannot be deserialized, then the attribute with the bad value will be where the line and position report.

  3. However, if the XML is well-formed and an element value cannot be deserialized, the XML reader will already have been advanced past the end of the element to the beginning of the next XML reader node (typically an element opening or closing), so the element causing the problem will be one one immediately before the reported location, possibly on the previous line.

  4. If the error is reported at (0, 0) then the reader was unable to begin parsing the XML. Likely problems include:

    • The encoding is wrong. See for instance How to change character encoding of XmlReader for an example.
    • You are reading from a string using StringReader and there is a BOM embedded at the beginning. See for instance XmlReader breaks on UTF-8 BOM for details.
    • The input is not XML at all. E.g. it's actually JSON, or a text message associated to an error response from a server.


来源:https://stackoverflow.com/questions/29880131/c-sharp-how-can-i-debug-a-deserialization-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!