0

I have a base class (eg)

[XmlType("address")]
[XmlInclude(typeof(AddressUK))]
[XmlInclude(typeof(AddressEurope))]
public class AddressBase
{
     // No serialized properties
}

and as you can see, I've decorated it to serialize to an element of 'address' and to expect some subclasses:

public class AddressUK : AddressBase
{
    [XmlElement("company")]
    [AddressField(AddressFieldType.Organisation, Required = true, MaxSize = 60)]
    public string Company { get; set; }
}

public class AddressEurope : AddressBase
{
    [XmlElement("company")]
    [AddressField(AddressFieldType.Organisation, Required = true, MaxSize = 40)]
    public string Company { get; set; }
}

The only reason I have these subclasses is so that I can decorate them with custom AddressField attributes. (Each subclass potentially has different settings, and the base class has methods that populates the address fields based on these attributes). Other than the AddressField attributes, these sub classes should serialize identically

But when I do serialize this my address node serializes as (eg)

...
<address p5:type="AddressUK" xmlns:p5="http://www.w3.org/2001/XMLSchema-instance">
    <company>Company Name</company>
    ...

I'd really like it to just serialize as <address> without the type and namespace information. I suspect it's trying to help me there, as without that information I wouldn't be able to deserialize it correctly, but for my scenario (integration with 3rd party provider) that information is redundant and not expected by them (and I don't need to deserialize in such an awkward way)

Is this possible, or am I approaching this from entirely the wrong angle?

dbc
  • 104,963
  • 20
  • 228
  • 340
PaulG
  • 13,871
  • 9
  • 56
  • 78
  • 1
    This is not possible, Imagine you wanted to deserialize the file. From where should the compiler know the actual type to infer? However you may add a post-processing onto your file deleting this stuff. – MakePeaceGreatAgain Mar 01 '16 at 11:39
  • `XmlSerializer` will never serialize a class unless it can also deserialize it. It puts the `{http://www.w3.org/2001/XMLSchema-instance}type` there in order to make this possible, so that it can know the type of class to deserialize to. See [Xsi:type Attribute Binding Support](https://msdn.microsoft.com/en-us/library/ca1ks327.aspx). Only workaround I can think of would be to take the `ElementSkippingXmlTextWriter` from https://stackoverflow.com/questions/32149676/custom-xmlwriter-to-skip-a-certain-element/32150990 and add the ability to skip attributes. Would that be useful? – dbc Mar 06 '16 at 17:08
  • Thanks guys. For the moment I'm taking the clumsy approach of `Regex.Replace(xmlString, "
    ", "
    ")` during serialization. In hindsight I'd have found a different way to tackle the underlying problem, so that I didn't have inherited classes with identical property names.
    – PaulG Mar 07 '16 at 14:33

0 Answers0