如何使用属性"序列化为"集合?使用XML Serializer

时间:2014-09-24 00:02:29

标签: c# xml serialization xml-serialization

我有这个型号:

[XmlArray(ElementName = "Listing")]
[XmlArrayItem(ElementName = "Classification")]
public List<Classification> classifications { get; set; }

[XmlRoot("Listing")]
public class Classification
{
     [XmlAttribute("Name")]
     public string name { get; set; }

     [XmlText]
     public string Value { get; set; }
}

这给了我这个:

<Listing>
<Classification Name="Location">AsiaPacific</Classification>
</Listing>

我应该如何修改我的课程来获得这个:

<Listing reference = "MyReference">
<Classification Name="Location">AsiaPacific</Classification>
</Listing>

1 个答案:

答案 0 :(得分:1)

经过几次(数百次)试验和错误后,我通过修改模型得到了我需要的结果:

[XmlElement(ElementName = "Listing")]
public ClassificationWrapper classificationWrapper { get; set; }

public class ClassificationWrapper
{
    [XmlAttribute("reference")]
        public string ref= "MyReference";

        [XmlElement("Classification", typeof(Classification))]
        public List<Classification> classifications { get; set; }

public ClassificationWrapper() { this.classifications = new List<Classification>(); }
}
public class Classification
{
       [XmlAttribute("Name")]
       public string name { get; set; }

       [XmlText]
       public string Value { get; set; }
}