1

I have been asked to debug code that uses the Deserialize Method in the XmlSerializer class to deserialize a string with a large and complicated XML into a large and complicated C# object with a given type.

The XML document comes from customers. Often the XML document has problems so it cannot be deserialized properly. For example, it may have a non-numeric value that has to go into a numeric field somewhere.

When Deserialize finds a problem it throws an exception, but that doesn't tell me which XML element and what value are causing the issue. This makes finding the problem in the XML document very time consuming.

Is there some way or tool to help me pinpoint the specific XML element and/or value in the XML document?

user1147862
  • 4,096
  • 8
  • 36
  • 53
  • 2
    [Using an XSD...](http://stackoverflow.com/questions/259726/can-i-fail-to-deserialize-with-xmlserializer-in-c-sharp-if-an-element-is-not-fou) – CodeCaster Dec 01 '15 at 09:47
  • See [Troubleshooting Common Problems with the XmlSerializer](https://msdn.microsoft.com/en-us/library/aa302290.aspx). Also, in my experience, exceptions from `XmlSerializer` usually *do* give the XML line number with an explanation of the problem. Do you have an example where this does not happen? – dbc Dec 01 '15 at 21:39
  • @dbc Thanks, I read that page (which does have some interesting info), but it wasn't of much use in my particular case. The exception indeed tells you what went wrong (in my case, conversion of a string to a number), but doesn't give you a line number or field name. – user1147862 Dec 02 '15 at 08:18
  • I can't reproduce your problem. See https://dotnetfiddle.net/lfnUKU. In `There is an error in XML document (X, Y)`, "(X, Y)" are the 1-based line and character positions of the `XmlReader` when the exception occurred. For format exceptions, the reader will already have been advanced to the next token, so the error is just BEFORE the stated position. – dbc Dec 02 '15 at 19:03

1 Answers1

3

Turns out that the diagnostics info in the exception is much better when you deserialize a string rather than an XML document.

I was trying to deserialize an XML doc:

// Deserializing XML document, exceptions don't give line numbers or fields 
XmlNode rootNode = ... XML document ... 
using (var reader = new XmlNodeReader(rootNode))
{
    var serializer = new XmlSerializer(typeof (T));
    return (T) serializer.Deserialize(reader);
}

However, I found that if you deserialize a string, you get the line number (within the XML string) where the offending element lives.

// Deserializing XML string, exceptions now give line number    
string serializedXmlString = .... XML string ...
using (var reader = new StringReader(serializedXmlString))
{
    var serializer = new XmlSerializer(typeof(T));
    return (T)serializer.Deserialize(reader);
}
user1147862
  • 4,096
  • 8
  • 36
  • 53