2014-06-27 130 views
0

我有一个.net Web Api 2应用程序,它以XML形式提供数据。用父节点包装XML根节点

我的问题:

我的一个班是这样的:

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

当我序列化此,其结果是:

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

我要的是包装所有外发具有这样的根元素的XML内容:

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

我一直希望在自定义的XmlFormatter中做到这一点。但我似乎无法弄清楚如何在writestream上附加一个根元素。

解决此问题的最佳方法是什么?

我已经尝试调整这个答案在我的自定义xmlserializer工作,但似乎并没有工作。 How to add a root node to an xml?

(我有时间来写这个问题的一个非常短的量,所以如果有任何遗漏,请发表评论。)

回答

0

所以..调整了这个问题的答案:How to add a root node to an xml?一起工作我XmlFormatter。

下面的代码工作,虽然我觉得这是一个骇人听闻的方法。

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); 
      } 
     }); 
    }