Xml-serializer是您所需要的。我用我發現和我的XML響應略微調整了這個XmlResult級需要:
public class XmlResult : ActionResult
{
private object objectToSerialize;
/// <summary>
/// Initializes a new instance of the <see cref="XmlResult"/> class.
/// </summary>
/// <param name="objectToSerialize">The object to serialize to XML.</param>
public XmlResult(object objectToSerialize)
{
this.objectToSerialize = objectToSerialize;
}
/// <summary>
/// Gets the object to be serialized to XML.
/// </summary>
public object ObjectToSerialize
{
get { return this.objectToSerialize; }
}
/// <summary>
/// Serialises the object that was passed into the constructor to XML and writes the corresponding XML to the result stream.
/// </summary>
/// <param name="context">The controller context for the current request.</param>
public override void ExecuteResult(ControllerContext context)
{
if (this.objectToSerialize != null)
{
context.HttpContext.Response.Clear();
XmlRootAttribute root = new XmlRootAttribute("response");
var xs = new System.Xml.Serialization.XmlSerializer(this.objectToSerialize.GetType(), root);
context.HttpContext.Response.ContentType = "text/xml";
xs.Serialize(context.HttpContext.Response.Output, this.objectToSerialize);
}
}
然後,每當你想從你的行動返回XML,你可以簡單地做:
public ActionResult GetStuffAsXml(int id)
{
var dbStuff = db.GetStuff(id);
// fetch stuff in database
return new XmlResult(dbStuff);
}
希望有幫助!
這有幫助,謝謝!怎麼樣反向 - 從序列化XML到對象? – Evan 2010-08-10 17:17:32
查看Xmlserializer上的Deserialize-method ..只要xml匹配對象,它就非常簡單直接... – 2010-08-10 19:44:56