【问题标题】:Can I serialize Xml for an MVC Web API without an object type?我可以为没有对象类型的 MVC Web API 序列化 Xml 吗?
【发布时间】:2013-07-16 14:33:46
【问题描述】:

所以我正在编写我的第一个 mvc 页面,并且我正在尝试编写一系列路由以允许报告系统创建简单的报告。 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 = new 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 的操作,但能够在没有对象类型的情况下对其进行序列化并返回它,而不必担心自定义可序列化对象类型。

【问题讨论】:

  • 浏览器根据响应的ContentType 解释内容。您可以更改Response.ContentType 以通知浏览器响应类型为text/xml

标签: c# .net xml


【解决方案1】:

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

【讨论】:

  • 如果我没有响应变量怎么办?我有 HttpResponse,但没有必要的方法。
猜你喜欢
  • 1970-01-01
  • 2011-01-25
  • 1970-01-01
  • 2011-12-11
  • 1970-01-01
  • 1970-01-01
  • 2011-01-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多