简体   繁体   中英

XmlSerializer throws an exception on enum

With the following Code the XmlSerializer throws an expection because Foo contains two Properties with the same name of the enum EnumSameName .

Framework .NET 4.0

public class Bar1
{
    public enum EnumSameName
    {
        a
    }

    public EnumSameName MyBar1Enum { get; set; }
}

public class Bar2
{
    public enum EnumSameName
    {
        b
    }

    public EnumSameName MyBar2Enum { get; set; }
}

public class Foo
{
    public Foo()
    {
        MyEnum1 = new Bar1();
        MyEnum2 = new Bar2();
    }

    public Bar1 MyEnum1 { get; set; }

    public Bar2 MyEnum2 { get; set; }
}

Now try to serialize Foo

var parameter = new Foo();
var serializer = new XmlSerializer(parameter.GetType()); 
// ERROR System.InvalidOperationException: [...]

After rename one of the EnumSameName everything works as expected.

Where does this error come from?

The error message in question should read

Types 'Bar2.EnumSameName' and 'Bar1.EnumSameName' both use the XML type name, 'EnumSameName', from namespace ''. Use XML attributes to specify a unique XML name and/or namespace for the type.

Have a look at

XML Namespace Collisions, XmlNodeList and Deserialization, and More

You can try to change the code to

[XmlRoot("Bar1", Namespace = "http://example.com/schemas/Bar1")]
public class Bar1
{
    [XmlRoot("Bar1EnumSameName", Namespace = "http://example.com/schemas/Bar1")]
    public enum EnumSameName
    {
        a
    }

    public EnumSameName Mode { get; set; }
}

[XmlRoot("Bar2", Namespace = "http://example.com/schemas/Bar2")]
public class Bar2
{
    [XmlRoot("Bar2EnumSameName", Namespace = "http://example.com/schemas/Bar2")]
    public enum EnumSameName
    {
        b
    }

    public EnumSameName Mode { get; set; }
}

As an after thought, just adding the XmlRoot documentation

Controls XML serialization of the attribute target as an XML root element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM