I have a model that I would like to serialize to an xml with specific properties.
Model:
public class MyClassModel
{
public int Id { get; set; }
public DateTime updated { get; set; }
}
The Code in the controller action:
IList<MyClassModel> objects = getStuff();
return new XmlResult(jaPropEstates); //Asp.net mvc class that is inherited from ActionResult
XmlResult class
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 se开发者_Go百科rialize 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();
var xs = new System.Xml.Serialization.XmlSerializer(this.objectToSerialize.GetType());
context.HttpContext.Response.ContentType = "text/xml";
xs.Serialize(context.HttpContext.Response.Output, this.objectToSerialize);
}
}
}
The output:
<ArrayOfMyClassModel>
<MyClassModel>
<Id>0</Id>
<updated>0001-01-01T00:00:00</updated>
</MyClassModel>
<MyClassModel>
<Id>2</Id>
<updated>0001-01-01T00:00:00</updated>
</MyClassModel>
I want it to be like this:
<?xml version="1.0" encoding="utf-8" ?> <!-- I want this -->
<listings xmlns="listings-schema"> <!-- I want ArrayOfMyClassModel to be renamed to this -->
<property> <!-- I want MyClassModel to be renamed to property -->
<Id>2</Id>
<updated>0001-01-01T00:00:00</updated>
</property>
</listings>
Note the difference as commented. How do I give my elements custom names?
Check out Proper way to implement IXmlSerializable. Gives you complete control over the XML serializer.
I'm assuming you have larger datasets by volume and complexity.
The first approach that comes to my mind is to get your output in an XmlDocument object then transform it against an XSL transformation.
OR System.Xml.Serialization.XmlSerializer
is another angle of approach.
See an example here
Your class is called "MyClassModel". If you want your xml element to be called "property" instead, rename your class to "property". However, you would be violating common naming conventions by using camel case instead of pascal case for your class.
精彩评论