2013-05-28 66 views
0

是否允許從[Serializable]屬性類過渡到IXmlSerializable類並返回?以下代碼按預期序列化,但不會反序列化A的第二個屬性(它總是返回null)。包含IXmlSerializable屬性的Serializable類無法反序列化?

謝謝!

using System.Xml.Serialization; 
using System.IO; 
using System; 

namespace Serialization 
{ 
    [Serializable] 
    public class A 
    { 
     public B B 
     { 
      get; 
      set; 
     } 

     public string C 
     { 
      get; 
      set; 
     } 
    } 

    public class B : IXmlSerializable 
    { 
     private int _value; 

     public void SetValue(int value) 
     { 
      _value = value; 
     } 

     public int GetValue() 
     { 
      return _value; 
     } 

     public System.Xml.Schema.XmlSchema GetSchema() 
     { 
      return null; 
     } 

     public void ReadXml(System.Xml.XmlReader reader) 
     { 
      int.TryParse(reader.ReadString(), out _value); 
     } 

     public void WriteXml(System.Xml.XmlWriter writer) 
     { 
      writer.WriteString(_value.ToString()); 
     } 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      A a = new A() {B = new B(), C = "bar"}; 
      a.B.SetValue(1); 

      XmlSerializer serializer = new XmlSerializer(typeof(A)); 
      Stream stream = File.Open("foo.xml", FileMode.Create); 
      serializer.Serialize(stream, a); 
      stream.Close(); 

      stream = File.Open("foo.xml", FileMode.Open); 

      A a1 = serializer.Deserialize(stream) as A; 

      if (a1.B.GetValue() != 1 || a1.C != "bar") 
      { 
       System.Diagnostics.Trace.WriteLine("Failed."); 
      } 
      else 
      { 
       System.Diagnostics.Trace.WriteLine("Succeeded."); 
      }    
     } 

    } 
} 

產生預期的XML:

<?xml version="1.0"?> 
<A xmlns:xsd="http://www.w3.org/2001/XMLSchema"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
<B>1</B> 
<C>bar</C> 
</A> 

回答

1

最近我有同樣的問題。我認爲這是因爲「reader.ReadString()」不會自己移動閱讀光標。你需要將它移到您完成後讀書,喜歡與

public void ReadXml(System.Xml.XmlReader reader) 
{ 
    int.TryParse(reader.ReadString(), out _value); 
    reader.Read(); 
} 

或者你可以使用下面的

public void ReadXml(System.Xml.XmlReader reader) 
{ 
    _value = reader.ReadElementContentAsInt(); 
} 

希望,這應該解決您的問題。

+0

謝謝!與任何一種解決方案完美配合。 – user2149714

相關問題