如何在序列化时重命名xml元素属性?

时间:2015-03-02 11:34:21

标签: .net xml xml-serialization xml-deserialization xml-attribute

我希望xml具有元素atrribute的自定义名称,我声明了名称如下所示

[XmlRoot(ElementName = "country")]
public class CountryInRegion
{
    [XmlElement(ElementName = "iso_code")]
    public string IsoCode { get; set; }

    [XmlElement(ElementName = "name")]
    public string Name { get; set; }

    [XmlElement(ElementName = "region_id")]
    public string RegionId { get; set; }
}

[XmlRoot(ElementName = "countries")]
public class Countries
{
    [XmlArray(ElementName = "country")]
    public IList<CountryInRegion> countries { get; set; }

    public Countries()
    {
        countries = new List<CountryInRegion>();
    }
}

我得到像这样的输出

<Countries>
 <countries>
  <CountryInRegion>
   <IsoCode>AD</IsoCode>
   <Name>Andorra</Name>
   <RegionId>EUROPE</RegionId></CountryInRegion>
  </CountryInRegion>
 </countries>
</Countries>

我也尝试了[XmlElement(“name”)]但没有获得任何更改

1 个答案:

答案 0 :(得分:0)

取决于如何从obj生成xml,您可能希望将类显式声明为[Serializable],请参阅What is [Serializable] and when should I use it?。你的重命名看起来很好。