Serialize c# object in XML using variable content as attribute name -


i have following c# object:

class modification {     public string name;     public string value; } 

i want use serializer serialize object following way:

<name>value</name> 

example: let's set variables to

name = "autoroute" value = 53 

i want xml like:

<test>     <autoroute>53</autoroute> </test> 

i saw somewhere feature not supported serializer, there way overload serializer allow kind of behavior ?

changing xml structure not option since convention.

you can use ixmlserializable this, though doesn't give control on root element name - have set in serializer (which may present other challenges when come read part of larger xml structure...).

public class modification : ixmlserializable {     public string name;     public string value;      public system.xml.schema.xmlschema getschema()     {         return null;     }      public void readxml(system.xml.xmlreader reader)     {         reader.readstartelement();         name = reader.name;         value = reader.readelementcontentasstring();         reader.readendelement();     }      public void writexml(system.xml.xmlwriter writer)     {         writer.writeelementstring(name, value);     } } 

usage,

modification modification = new modification() {     name = "autoroute",     value = "53" };  modification andback = null;  string rootelement = "test";     xmlserializer s = new xmlserializer(typeof(modification), new xmlrootattribute(rootelement)); using (streamwriter writer = new streamwriter(@"c:\temp\output.xml"))     s.serialize(writer, modification);  using (streamreader reader = new streamreader(@"c:\temp\output.xml"))     andback = s.deserialize(reader) modification;  console.writeline("{0}={1}", andback.name, andback.value); 

the xml produced looks this,

<?xml version="1.0" encoding="utf-8"?> <test>    <autoroute>53</autoroute> </test> 

Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -