0

I have a .net Web Api 2 application that delivers data in XML.

My problem:

One of my classes looks like this:

public class Horse
{
    public string Name { get;set; }
    public string Category { get;set; }
}

When i serialize this, the result is:

<Horse>
    <Name>Bobo</Name>
    <Category>LargeAnimal</Category>
</Horse>

What i want is to wrap all outgoing XML content with a root element like this:

<Animal>
   <Horse>
   .....
   </Horse>
</Animal>

I was hoping to do this in a custom XmlFormatter. But i can't seem to figure out how to append a root element on the writestream.

What is the best way to resolve this issue?

I have tried tweaking this answer to work in my custom xmlserializer, but doesn't seem to work. How to add a root node to an xml?

( I had a really short amount of time to write this question, so if anything is missing, please leave a comment.)

Community
  • 1
  • 1
Are Almaas
  • 1,063
  • 12
  • 26

1 Answers1

1

So.. Tweaked the answer to this question: How to add a root node to an xml? to work with my XmlFormatter.

The following code works, although i feel this is a 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 a temporary xml document
            var navigator = temp.CreateNavigator(); //use its navigator
            using (var w = navigator.AppendChild()) //to get an XMLWriter
                xs.Serialize(w, value);              //serialize your data to it

            XmlDocument xdoc = new XmlDocument();   //init the main xml document
             //add xml declaration to the top of the new xml document
            xdoc.AppendChild(xdoc.CreateXmlDeclaration("1.0", "utf-8", null));
            //create the root element
            var animal = xdoc.CreateElement("Animal");

            animal.InnerXml = temp.InnerXml;   //copy the serialized content
            xdoc.AppendChild(animal);

            using (var xmlWriter = new XmlTextWriter(writeStream, encoding))
            {
                xdoc.WriteTo(xmlWriter);
            }
        });
    }
Community
  • 1
  • 1
Are Almaas
  • 1,063
  • 12
  • 26