XmlSerializationException Class
The XmlSerializationException
class represents errors that occur during XML serialization or deserialization.
Namespace: System.Xml
Assembly: System.Xml.dll
Inheritance
System.Object → System.Exception → System.Xml.XmlSerializationException
Constructors
XmlSerializationException()
XmlSerializationException(string message)
XmlSerializationException(string message, Exception innerException)
Properties
Message
– Gets a message that describes the current exception.InnerException
– The exception that caused the current exception.StackTrace
– Gets a string representation of the immediate frames on the call stack.
Remarks
The XmlSerializationException
is thrown when the XmlSerializer
encounters an error that it cannot automatically resolve. Typical scenarios include:
- Missing parameterless constructors on a type being serialized.
- Incorrect use of
[XmlIgnore]
or other serialization attributes. - Invalid XML format that does not match the expected structure.
When catching this exception, inspect the InnerException
property for more detailed information.
Example
The following example demonstrates how to catch an XmlSerializationException
when deserializing an XML file.
using System;
using System.IO;
using System.Xml.Serialization;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
string xml = "<Person><Name>John</Name><Age>Thirty</Age></Person>";
try
{
var serializer = new XmlSerializer(typeof(Person));
using var reader = new StringReader(xml);
var person = (Person)serializer.Deserialize(reader);
}
catch (XmlSerializationException ex)
{
Console.WriteLine($"Serialization error: {ex.Message}");
if (ex.InnerException != null)
Console.WriteLine($"Inner exception: {ex.InnerException.Message}");
}
}
}