2013-07-16 30 views
0

因此,我正在寫我的第一個MVC頁面,並且我正在嘗試編寫一系列路線以允許報告系統創建簡單的報告。 XML是小的,這裏有一個例子:我可以在沒有對象類型的情況下爲MVC Web API序列化Xml嗎?

<xml><root><item><value>23</value></item></root> 

我嘗試這樣做:

 using (StringWriter xmlStringWriter = new StringWriter()) 
     { 
      using (XmlWriter xmlWriter = XmlWriter.Create(xmlStringWriter)) 
      { 

        XmlWriter.WriteStartElement("root") 
        ... 
      } 
      return xmlStringWriter.ToString(); 
     } 

但這顯然返回一個字符串,而不是由瀏覽器解釋爲XML。我也知道*如果你返回一個可序列化的對象,那麼瀏覽器就知道把它解釋爲xml或json。所以,我試圖限定的一組對象保持彼此在XML嵌套的方式:

[Serializable] 
public class XmlReportRoot 
{ 
    [System.Xml.Serialization.XmlAttribute("root")] 
    public List<XmlReportItem> item { get; set; } 

} 

[Serializable] 
public class XmlReportItem 
{ 
    [System.Xml.Serialization.XmlAttribute("item")] 
    public XmlReportValue value { get; set; } 

} 

[Serializable] 
public class XmlReportValue 
{ 
    [System.Xml.Serialization.XmlAttribute("value")] 
    public string count { get; set; } 
} 

和: XmlReportRoot xmlRoot =新XmlReportRoot();

 XmlReportItem xmlItem = new XmlReportItem(); 
     List<XmlReportItem> itemList = new List<XmlReportItem>(); 

     itemList.Add(xmlItem); 

     XmlReportValue xmlValue = new XmlReportValue(); 
     xmlValue.count = newCustomers.ToString(); 

     xmlItem.value = xmlValue; 

     xmlRoot.item = itemList; 

     XmlSerializer xmlSer = new XmlSerializer(typeof(XmlReportRoot)); 
     xmlSer.Serialize(xmlRoot); //this line doesn't work 

但這只是感覺錯了,我不能完全讓序列化工作,而不用擔心文件流,我寧願這樣做。

所以我想我正在試圖找到一種方法來做一些像XmlWriter,但能夠序列化,沒有對象類型,並返回,而不必擔心自定義可序列化的對象類型。

+0

瀏覽器解釋基於響應的'ContentType'內容。您可以更改'Response.ContentType'來通知瀏覽器響應是'text/xml'類型。 –

回答

4

使用XmlWriter.Create(Response.OutputStream)Response.ContentType = "application/xml"

+0

如果我沒有響應變量會怎麼樣?我有HttpResponse,但沒有必要的方法。 – dckuehn

+1

HttpContext.Current.Response可以工作.. – Steve

相關問題