In C#, I’m trying to serialize ClassA into XML:
[Serializable]
public ClassA
{
[XmlElement]
public string PropertyA { get; set; } // works fine
[XmlElement]
public ClassB MyClassB { get; set; }
}
[Serializable]
public ClassB
{
private string _value;
public override string ToString()
{
return _value;
}
}
Unfortunately, the serialized result is:
<PropertyA>Value</PropertyA>
<ClassB />
Instead, I want it to be:
<PropertyA>Value</PropertyA>
<ClassB>Test</ClassB>
…assuming _value == "Test". How do I do this? Do I have to provide a public property in ClassB for _value? Thanks!
UPDATE:
By implementing the IXmlSerializable interface in ClassB (shown here #12), the following XML is generated:
<PropertyA>Value</PropertyA>
<ClassB>
<Value>Test</Value>
</ClassB>
This solution is almost acceptable, but it would be nice to get rid of the tags. Any ideas?
As you indicated, the only way to do this is to implement the IXmlSerializable interface.
Serializing the following instance…
will return the following xml :
You might want to do some validations so that you encode xml tags etc.