How do I Deserialize xml document with namespaces using XmlSerializer?

angrifel picture angrifel · Oct 17, 2011 · Viewed 11k times · Source

When deserializing a document using XmlSerializer are not deserialized correctly

Document

<?xml version=\"1.0\"?>
<ns0:ElementA xmlns:ns0=\"urn:some-namespace\">
    <Prop1>Some Value</Prop1>
    <Prop2>Some other value</Prop2>
</ns0:ElementA>

Class

[XmlRoot(Namespace = "urn:some-namespace")]
public class ElementA
{
    [XmlElement]
    public string Prop1 { get; set; }

    [XmlElement]
    public string Prop2 { get; set; }
}

Both Prop1 and Prop2 are null at the end of the deserialization.

I cannot change the structure of the document to get rid of the namespace so I need to handle the deserialization properly on my side.

The document has been simplified for the purpose of reproduction

How should I set the attributes on the ElementA to handle the deserialization correctly??

-- Here is the full code for reproducing the problem --

namespace ConsoleApplication1
{
    using System;
    using System.IO;
    using System.Xml.Serialization;

    public class Program
    {
        [XmlRoot(Namespace = "urn:some-namespace")]
        public class ElementA
        {
            [XmlElement]
            public string Prop1 { get; set; }

            [XmlElement]
            public string Prop2 { get; set; }
        }

        static void Main(string[] args)
        {
            var element =
                "<?xml version=\"1.0\"?>" + Environment.NewLine +
                "<ns0:ElementA xmlns:ns0=\"urn:some-namespace\">" + Environment.NewLine+                    "    <Prop1>Some Value</Prop1>" + Environment.NewLine +
                "    <Prop2>Some other value</Prop2>" + Environment.NewLine +
                "</ns0:ElementA>";

            XmlSerializer serializer = XmlSerializer.FromTypes(new[] { typeof(ElementA) })[0];
            ElementA result;

            using (var reader = new StringReader(element))
            {
                result = serializer.Deserialize(reader) as ElementA;
            }

            Console.WriteLine("Prop1: " + result.Prop1);
            Console.WriteLine("Prop2: " + result.Prop2);
            Console.ReadKey();
        }
    }
}

Answer

Marc Gravell picture Marc Gravell · Oct 17, 2011

Originally posted as a comment, since I haven't verified it, but:

<Prop1>Some Value</Prop1>

is not the same as

<ns0:Prop1>Some Value</ns0:Prop1>

So to get it working, you probably just need:

[XmlElement(Namespace="")]
public string Prop1 { get; set; }

[XmlElement(Namespace="")]
public string Prop2 { get; set; }