How Can I Serialize Entities From An Asp.net Mvc Site To Xml?
I am working on an ASP.NET MVC (in c#) site which connects to a database and takes advantage of the entities framework. I'd like people to be able to modify the information in the
Solution 1:
The Xml-serializer is all you need. I'm using this XmlResult-class that I've found and tweaked slightly for my XML-response needs:
publicclassXmlResult : ActionResult
{
privateobject objectToSerialize;
///<summary>/// Initializes a new instance of the <see cref="XmlResult"/> class.///</summary>///<param name="objectToSerialize">The object to serialize to XML.</param>publicXmlResult(object objectToSerialize)
{
this.objectToSerialize = objectToSerialize;
}
///<summary>/// Gets the object to be serialized to XML.///</summary>publicobject ObjectToSerialize
{
get { returnthis.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>publicoverridevoidExecuteResult(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);
}
}
Then, whenever you want to return XML from your Action you can simply do:
public ActionResult GetStuffAsXml(int id)
{
var dbStuff = db.GetStuff(id);
// fetch stuff in databasereturnnew XmlResult(dbStuff);
}
Hope that helps!
Solution 2:
Try these two links to get you started xml serializerWCF documentation
Even though you have to add the WCF attributes when you may not be using WCF it can simplify the processing of the data. In my opinion it's usually better to pass this onto a trusted library where possible to prevent you being bogged down in the details
Post a Comment for "How Can I Serialize Entities From An Asp.net Mvc Site To Xml?"