views:

172

answers:

1

I am learning XML Serialization and meet an issue, I have two claess

[System.Xml.Serialization.XmlInclude(typeof(SubClass))]
public class BaseClass
{

}

public class SubClass : BaseClass
{
}

I am trying to serialize a SubClass object into XML file, I use blow code

XmlSerializer xs = new XmlSerializer(typeof(Base));
xs.Serialize(fs, SubClassObject);

I noticed Serialization succeed, but the XML file is kind of like

<?xml version="1.0"?>
<BaseClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:type="SubClass">
...
</Employee>

If I use

XmlSerializer xs = new XmlSerializer(typeof(Base));
SubClassObject = xs.Deserialize(fs) as SubClass;

I noticed it will complain xsi:type is unknown attribute(I registered an event), although all information embedded in the XML was parsed successfully and members in SubClassObject was restored correctly.

Anyone has any idea why there is error in parsing xsi:type and anything I did wrong?

Thanks

+1  A: 

Here is the program that I wrote

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace XmlIncludeExample
{
    [XmlInclude(typeof(DerivedClass))]
    public class BaseClass
    {
        public string ClassName = "Base Class";
    }

    public class DerivedClass : BaseClass
    {
        public string InheritedName = "Derived Class";
    }

    class Program
    {
        static void Main(string[] args)
        {
            string fileName = "Test.xml";
            string fileFullPath = Path.Combine(Path.GetTempPath(), fileName);

            try
            {
                DerivedClass dc = new DerivedClass();

                using (FileStream fs = new FileStream(fileFullPath, FileMode.CreateNew))
                {
                    XmlSerializer xs = new XmlSerializer(typeof(BaseClass));
                    xs.Serialize(fs, dc);
                }

                using (FileStream fs = new FileStream(fileFullPath, FileMode.Open))
                {
                    XmlSerializer xs = new XmlSerializer(typeof(BaseClass));
                    DerivedClass dc2 = xs.Deserialize(fs) as DerivedClass;
                }
            }
            finally
            {
                if (File.Exists(fileFullPath))
                {
                    File.Delete(fileFullPath);
                }
            }
        }
    }
}

This produced the following xml

<?xml version="1.0" ?> 
- <BaseClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:type="DerivedClass">
  <ClassName>Base Class</ClassName> 
  <InheritedName>Derived Class</InheritedName> 
  </BaseClass>

And it worked

KD