ASP.NET MVC:C#自定义将对象列表序列化为xml

时间:2010-11-27 21:16:42

标签: asp.net-mvc xml-serialization

我有一个模型,我想序列化为具有特定属性的xml。

型号:

public class MyClassModel
{
    public int Id { get; set; }
    public DateTime updated { get; set; }
}

控制器操作中的代码:

IList<MyClassModel> objects = getStuff();
return new XmlResult(jaPropEstates); //Asp.net mvc class that is inherited from ActionResult

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();
            var xs = new System.Xml.Serialization.XmlSerializer(this.objectToSerialize.GetType());
            context.HttpContext.Response.ContentType = "text/xml";
            xs.Serialize(context.HttpContext.Response.Output, this.objectToSerialize);
        }
    }
}

输出:

<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>

我希望它是这样的:

<?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>

注意差异为评论。如何为我的元素提供自定义名称?

3 个答案:

答案 0 :(得分:3)

结帐Proper way to implement IXmlSerializable。使您可以完全控制XML序列化程序。

答案 1 :(得分:1)

我假设您按数量和复杂性拥有更大的数据集。

我想到的第一种方法是将输出放在XmlDocument对象中,然后将其转换为 XSL 转换。

OR System.Xml.Serialization.XmlSerializer是另一种接近的角度。

查看示例here

答案 2 :(得分:0)

您的班级名为“MyClassModel”。如果您希望将xml元素称为“property”,请将您的类重命名为“property”。但是,如果您的班级使用驼峰案例而不是pascal案例,则会违反常见的命名约定。