0

I am trying to deserialize and read a simple XML file, the following code finishes without error, but the deserialization was not performed.

My message has one node, three elements below that. After the Deserialize call, I am trying to read one of the properties and it is empty.

    public class Program
    {
        private string response = @"<?xml version=""1.0""?>
<ApplicationException xmlns = ""http://schemas.datacontract.org/2004/07/System"" xmlns:x=""http://www.w3.org/2001/XMLSchema"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"">
    <Name xmlns = """" i:type=""x:string"">System.ApplicationException</Name>
    <Message xmlns = """" i:type=""x:string"">Error Message 12345</Message>
    <DataPoints xmlns = """" i:nil=""true""/>
</ApplicationException>";
        private XElement xElement;
        private ExceptionClass theException;

        public TestXML()
        {
            xElement = XElement.Parse(response);
            var xmlSerializer = new XmlSerializer(typeof(ExceptionClass));
            using (var reader = xElement.CreateReader())
            {
                theException = (ExceptionClass)xmlSerializer.Deserialize(reader); 
            }
            Console.WriteLine(theException.Message); // nothing is showing up
        }
    }

    [XmlRoot(Namespace = "http://schemas.datacontract.org/2004/07/System", 
             ElementName = "ApplicationException")]
    public class ExceptionClass
    {
        public String Name { get; set; }
        public String Message { get; set; }
        public String DataPoints { get; set; }
    }
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Olivier De Meulder
  • 2,493
  • 3
  • 25
  • 30

1 Answers1

1

The problem is you are setting the XML namespaces of the elements to null whereas the root element has a namespace. Try this:

public class ExceptionClass
    {
        [XmlElement(Namespace="")]
        public String Name { get; set; }
        [XmlElement(Namespace = "")]
        public String Message { get; set; }
        [XmlElement(Namespace = "")]
        public String DataPoints { get; set; }
    }

That should work...

Matt
  • 6,787
  • 11
  • 65
  • 112