Double属性不会序列化为XML

时间:2012-10-09 14:50:55

标签: c# .net xml xml-serialization double

我们将对象序列化为xml:

   public class Test: INotifyPropertyChanged
   {
       public virtual string Name {get; set;}
       public virtual double TestScore {get; set;}
   }

使用以下方法:

public static XElement ToXElement<T>(this object obj)
{
    using (var memoryStream = new MemoryStream())
    {
        using (TextWriter streamWriter = new StreamWriter(memoryStream))
        {
            var xmlSerializer = new XmlSerializer(typeof(T));
            xmlSerializer.Serialize(streamWriter, obj);
            return XElement.Parse(Encoding.UTF8.GetString(memoryStream.ToArray()));
        }
    }
}

在以下上下文中(代码在x64上下文中运行,从C ++库中调用.net库):

XDocument rootElement = ...

Test test = new Test();
test.Name = "xxx";
test.TestScore= 1.0d;
rootElement.Add(test.ToXElement());

除double属性外,所有类型的属性(string,bool,long,int,ushort等)都是序列化的。一旦手动转换为其他东西(不是双倍),它们将被序列化。

Xml看起来像这样:

<Root>
  <Test>
    <Name>xxx</Name>
  </Test>
</Root>

有没有理由说明为什么不会对双重属性进行序列化?

1 个答案:

答案 0 :(得分:3)

要定义序列化的准确程度,您应该手动设置。

[XmlIgnore]
public double Price { get;set; }

[XmlElement("Price")]
public string PriceString {
    get {return Price.ToString();}
    set {Price = double.Parse(value);}
}

来自http://bytes.com/topic/c-sharp/answers/768555-serializable-double-precision