问题
I am somehow not able to achieve this serialization. I have these classes
public class Data
{
[XmlElement("Name")]
public string Name { get; set; }
}
[XmlRoot("Data")]
public class DataA : Data
{
[XmlElement("ADesc")]
public string ADesc { get; set; }
}
[XmlRoot("Data")]
public class DataB : Data
{
[XmlElement("BDesc")]
public string BDesc { get; set; }
}
When I serialize either DataA or DataB I should get the XMLs in the below structure:
<Data xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="" i:type="DataA">
<Name>A1</Name>
<ADesc>Description for A</ADesc>
</Data>
<Data xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="" i:type="DataB">
<Name>B1</Name>
<BDesc>Description for b</BDesc>
</Data>
What I am getting is the below (without the i:type="..." and xmlns="")
<Data xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Name>A1</Name>
<ADesc>Description for A</ADesc>
</Data>
<Data xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Name>B1</Name>
<BDesc>Description for b</BDesc>
</Data>
I am not sure what I am missing here. any suggestions would be helpful.
- Girija
回答1:
You should include the derived types for XML Serialization of the base class.
Then you can create a serializer for the base type, and when you serialize any derived type, it will add the type attribute: (You can even remove the [Root] sttribute from the derived classes now)
[XmlInclude(typeof(DataA))]
[XmlInclude(typeof(DataB))]
[XmlRoot("Data", Namespace = Data.XmlDefaultNameSpace)]
public class Data
{
public const string XmlDefaultNameSpace = "http://www.stackoverflow.com/xsd/Data";
[XmlElement("Name")]
public string Name { get; set; }
}
Serialization:
DataA a = new DataA() { ADesc = "ADesc", Name = "A" };
DataB b = new DataB() { BDesc = "BDesc", Name = "B" };
new XmlSerializer(typeof(Data)).Serialize(Console.OpenStandardOutput(), a);
new XmlSerializer(typeof(Data)).Serialize(Console.OpenStandardOutput(), b);
Here is the output for DataA class serialization
<?xml version="1.0"?>
<Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:type="DataA" xmlns="http://www.stackoverflow.com/xsd/Data">
<Name>A</Name>
<ADesc xmlns="">ADesc</ADesc>
来源:https://stackoverflow.com/questions/33567824/serialize-derived-class-root-as-base-class-name-with-type