MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

XML-serialization with derived types

I´ve again a problem on getting my serializer to work. I have a baseclass A and a derived class B:

class Program
{
    static void Main(string[] args)
    {
        A foo = new B();

        // determine that the class B overrides A
        XmlAttributeOverrides overrides = new XmlAttributeOverrides();
        overrides.Add(typeof(A), new XmlAttributes
        {
            XmlElements = { new XmlElementAttribute("B", typeof(B)) }
        });

        XmlSerializer ser = new XmlSerializer(typeof(A), overrides);
        ser.Serialize(new XmlTextWriter("test.xml", Encoding.Default), foo);

    }
}

public class A { public int a;}
public class B : A { public int b;}

But when I run this little program I get exception

XmlRoot and XmlType attributes may not be specified for the type ConsoleApplication1.A

but I never determined the root or type-attribute for class A so I´m really confused about this message. Is there anything behind the scenes I have to specify? All I want do is serialize an instance of B that simply add some properties to the definition of A...

Upvotes: 2

Views: 2511

Answers (2)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

I finally got two solutions to work:

Number 1:

...
XmlSerializer ser = new XmlSerializer(typeof(A));
ser.Serialize(new XmlTextWriter("test.xml", Encoding.Default), foo);
...         

[System.Xml.Serialization.XmlRoot("Root", Namespace = "DefaultNS")]
[System.Xml.Serialization.XmlInclude(typeof(B))]
public class A { public int a;}

[System.Xml.Serialization.XmlRoot(Namespace = "CustomNS")]
public class B : A { public int b;}

Number 2 (in addition to Ondrejs solution):

...
XmlSerializer ser = new XmlSerializer(typeof(A), overrides, new[] { typeof(B) }, new XmlRootAttribute("Root"), "defautlNS");
...

public class A { public int a;}
public class B : A { public int b;}

The second one in contrast to the first solution has the disadvantage that you may not see where an attribute within the XML-document comes from (from defaultNS or customNS) since you cannot specify any customNS.

Upvotes: 2

Ondrej Janacek
Ondrej Janacek

Reputation: 12616

It is right there in the error message you are getting.

XmlRoot and XmlType attributes may not be specified for the type ConsoleApplication1.A

You have to specify a root element for the output xml document.

Replace

overrides.Add(typeof(A), new XmlAttributes

with

overrides.Add(typeof(A), "node", new XmlAttributes

And you will have to probably also replace

new XmlSerializer(typeof(A), overrides);     

with

new XmlSerializer(typeof(B), overrides);

For more info and example on overriding, please visit MSDN.

Upvotes: 4

Related Questions