c# - Serialize a derived type without the type and namespace attributes -


i have xml api have mimic character character. i'm trying use built-in xml serialization functionality in .net, it's adding attributes. in normal web service or xml api, these attributes wouldn't hurt , might serve purpose. unexpected characters and, unfortunately, cannot allow them. here's i'd (with hypothetical objects of course):

i have base type

public abstract class instrument { }

...and have derived type

public class guitar : instrument { }

...and serialize derived type this:

<guitar />

instead, this:

<instrument d1p1:type="guitar" xmlns:d1p1="http://www.w3.org/2001/xmlschema-instance" />

here's test i'm working with:

[testclass] public class when_serializing_a_guitar {     private xmlserializer _serializer;     private string _expectedxml;     private stringwriter _stringwriter;     private string _actualxml;     private xmlserializernamespaces _ns;     private xmlwriter _xmlwriter;      private void withthiscontext()     {         _ns = new xmlserializernamespaces();         _ns.add("", "");          _stringwriter = new stringwriter();         _xmlwriter = xmlwriter.create(_stringwriter, new xmlwritersettings                                                          {                                                              omitxmldeclaration = true,                                                              closeoutput = false                                                          });          _serializer = new xmlserializer(typeof(instrument), new[] { typeof(guitar) });          _expectedxml = @"<guitar />";     }      private void becauseofthisaction()     {         _serializer.serialize(_xmlwriter, new guitar(), _ns);         _actualxml = _stringwriter.tostring();     }      [testmethod]     public void it_should_return_the_expected_properly_formatted_xml()     {         withthiscontext();         becauseofthisaction();         assert.areequal(_expectedxml, _actualxml);     } } 

know how can this?

i'm assuming need keep domain model hierarchy intact. otherwise this: var serializer = new xmlserializer(typeof (guitar));

if need keep intact, suggest write own toxml methods on each of domain objects.

public interface ixmlwritable {     string toxml(); }  public class instrument : ixmlwritable {     public string classification { get; set; }      public string toxml()     {         return "<instrument classification='" + classification + "' />";     } } 

or depending on how want iterate through nodes.


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -