C#.Net中的XML序列化,序列化所有类属性

时间:2011-09-05 14:57:26

标签: c# .net xml xml-serialization linq-to-xml

我想序列化这个课程:

[Serializable]
[XmlRoot(ElementName = "Rates")]
public class CbrRate : IRate
{
    public CbrRate()
    {
    }

    public CbrRate(DateTime date, ICurrency currency, decimal rate)
    {
        Currency = currency;
        Date = date;
        Rate = rate;
    }

    [XmlIgnore]
    public string SrcName
    {
        get { return "CBR"; }
    }

    [XmlElement(ElementName = "RequestDate")]
    public DateTime Date { get; set; }

    [XmlIgnore]
    public ICurrency Currency { get; set; }

    [XmlElement(ElementName = "Direction")]
    public string Direction
    {
        get { return "RUR=>" + CodeChar.Trim(); }
    }

    [XmlElement(ElementName = "RateValue")]
    public decimal Rate { get; set; }

    [XmlElement(ElementName = "RateBase")]
    public decimal BaseRate
    {
        get { return Math.Round(Rate/Nominal, 4); }
    }

    [XmlElement(ElementName = "RateCross")]
    public decimal CrossRate
    {
        get { return Math.Round(1.00M/BaseRate, 4); }
    }

    [XmlElement(ElementName = "CodeNum")]
    public int CodeNum
    {
        get { return Currency.CodeNumIso; }
    }

    [XmlElement(ElementName = "CodeISO")]
    public string CodeChar
    {
        get { return Currency.CodeCharIso; }
    }

    [XmlElement(ElementName = "CurrencyName")]
    public string Name
    {
        get { return Currency.Name; }
    }

    [XmlElement(ElementName = "Nominal")]
    public decimal Nominal
    {
        get { return Currency.Nominal; }
    }
}


public static XDocument Serialize<T>(this T source)
{
    var target = new XDocument();
    var s = new XmlSerializer(typeof (T));
    using (var writer = target.CreateWriter())
    {
        s.Serialize(writer, source);
        writer.Close();
    }
    return target;
}

但是,我有:

<?xml version="1.0" encoding="utf-16"?>
<ArrayOfCbrRate xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <CbrRate>
    <RequestDate>2011-09-05T18:49:55.1195696+04:00</RequestDate>
    <RateValue>31.0539</RateValue>
  </CbrRate>
...

如何创建正确的xml,如下所示:

<ArrayOfRates>    
<Rates>
       <RequestDate></RequestDate>
       <Direction></Direction>
       <RateValue></RateValue>
       <RateBase></RateBase>
    ...

2 个答案:

答案 0 :(得分:1)

因此,假设您正在序列化List<CbrRate >,您需要为列表创建一个包装类,以便根据需要对其进行序列化。像这样:

[XmlRoot("root")]
public class ListOfRates 
{
    [XmlArray("ArrayOfRates")]
    [XmlArrayItem("Rate")]
    public List<CbrRate> Rates { get; set; }
}

这将产生你想要的xml。或者你可以稍微使用属性,但如果你不想拥有根:

[XmlRoot("ArrayOfRates")]
public class ListOfRates 
{
    [XmlArrayItem("Rate")]
    public List<CbrRate> Rates { get; set; }
}

这两个属性XmlArrayXmlArrayItem是关键所在。如果没有为xml元素提供名称,则默认为属性名称。

答案 1 :(得分:1)

首先,.Net XmlSerializer只会序列化读/写属性(或字段)。这就是为什么只有RequestDateRateValue被序列化的原因。

为了实现你提到的XML结构,你需要像Roel所说的那样创建一个包装类。