c# - Wrap XML root node with parent node -


i have .net web api 2 application delivers data in xml.

my problem:

one of classes looks this:

public class horse {     public string name { get;set; }     public string category { get;set; } } 

when serialize this, result is:

<horse>     <name>bobo</name>     <category>largeanimal</category> </horse> 

what want wrap outgoing xml content root element this:

<animal>    <horse>    .....    </horse> </animal> 

i hoping in custom xmlformatter. can't seem figure out how append root element on writestream.

what best way resolve issue?

i have tried tweaking answer work in custom xmlserializer, doesn't seem work. how add root node xml?

( had short amount of time write question, if missing, please leave comment.)

so.. tweaked answer question: how add root node xml? work xmlformatter.

the following code works, although feel hackish approach.

public override task writetostreamasync(type type, object value, stream  writestream, httpcontent content, transportcontext transportcontext)     {         return task.factory.startnew(() =>         {             xmlserializer xs = new xmlserializer(type);              xmldocument temp = new xmldocument();   //create temporary xml document             var navigator = temp.createnavigator(); //use navigator             using (var w = navigator.appendchild()) //to xmlwriter                 xs.serialize(w, value);              //serialize data              xmldocument xdoc = new xmldocument();   //init main xml document              //add xml declaration top of new xml document             xdoc.appendchild(xdoc.createxmldeclaration("1.0", "utf-8", null));             //create root element             var animal = xdoc.createelement("animal");              animal.innerxml = temp.innerxml;   //copy serialized content             xdoc.appendchild(animal);              using (var xmlwriter = new xmltextwriter(writestream, encoding))             {                 xdoc.writeto(xmlwriter);             }         });     } 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -