2010-11-27 81 views
1

我有一个模型,我想序列化到具有特定属性的XML。ASP.NET MVC:C#自定义序列化对象列表到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> 

注意区别的评论。我如何给我的元素定制名称?

回答

1

我假设你有更大的数据集按体积和复杂性。

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

System.Xml.Serialization.XmlSerializer是另一种方法。

看到一个例子here

+0

第二个不显示如何从原始属性名称重命名节点。 – 2010-11-27 22:06:14

0

你的班级被称为“MyClassModel”。如果你想让你的xml元素被称为“property”,可以将你的类重命名为“property”。但是,对于您的课程,您将违反常规命名惯例,即使用骆驼案例而不是pascal案例。

+0

因此,没有办法在其上放置一个属性,所以它在xml中重命名,而不是重命名整个类?我必须遵循提供给我的公开数据的模式。 – 2010-11-28 03:08:14