2010-11-10 80 views
4

無法理解我做錯了什麼,結果集是空的。
我的代碼:Xml序列化c#

class Class1 
    { 

     public static object DeSerialize() 
     { 
      object resultObject; 

      XmlSerializer serializer = new XmlSerializer(typeof(PointsContainer)); 
      using (TextReader textReader = new StreamReader(@"d:\point.xml")) 
      { 
       resultObject = serializer.Deserialize(textReader); 
      } 

      return resultObject; 


     } 
    } 

    [Serializable] 
    [XmlRoot("Points")] 
    public class PointsContainer 
    { 
     [XmlElement("Point")]  
     private List<Point> items = new List<Point>(); 

     public List<Point> Items 
     { 
      get { return items; } 
      set { items = value; } 
     } 


    } 


    [Serializable] 
    public class Point 
    {  
     [XmlAttribute] 
     public bool x { get; set; } 

     [XmlAttribute] 
     public bool y { get; set; } 
    } 

XML:

<Points> 
    <Point x="1" y="5"/> 
    <Point x="21" y="3"/> 
    <Point x="3" y="7"/> 
</Points> 

回答

8

移動[XmlElement]屬性的屬性。
XmlSerializer忽略私有成員。

1

爲SLaks說

還貴點對象同時顯示領域的bool尚未值在XML文件中的整數至少爲(21,3,5,7等)

1

布爾變量可以是true或false,其整數值爲1和0.因此,您的XML具有無效數據和/或您的類屬性類型錯誤。

1
[XmlElement("Point")] 
public List<Point> Items 
{ 
    get { return items; } 
    set { items = value; } 
} 

而在你的觀點中,x和y都不應該是bools。

1

解決方案:

namespace XmlStackProblem 
{ 
    class Class1 
    { 

     public static void Main() 
     { 
      Points resultObject; 

      XmlSerializer serializer = new XmlSerializer(typeof(Points)); 
      using (TextReader textReader = new StreamReader(@"d:\points.xml")) 
      { 
       resultObject = serializer.Deserialize(textReader) as Points; 
      } 
     } 
    } 

    [Serializable] 
    [XmlRoot(IsNullable = false)] 
    public class Points 
    { 
     [XmlElementAttribute("Point")] 
     public List<Point> Point 
     { 
      get; set; 
     } 
    } 

    [Serializable] 
    [XmlType(AnonymousType = true)] 
    public class Point 
    { 
     [XmlAttribute] 
     public int x 
     { 
      get; 
      set; 
     } 

     [XmlAttribute] 
     public int y { get; set; } 
    } 
} 
+0

krystan有你做x和y字節。一個人可以考慮他們一個理由整數?我沒有看到製作x和y字節的好處,這意味着作者可以根據他們選擇的電線系統進行限制。 – 2010-11-10 20:33:02

+0

我把它作爲一個字節,因爲字符是一個字節大,它是我的習慣(快速編寫代碼時),這可能會更好地使它們成爲字符類型,因爲實際上是在xml中表示的,所以我接受你的改進,將類型改爲char將沒有任何區別,代碼仍然可以正常工作,你說的正確的說一個字節會限制作者,如果你必須的話,你總是可以轉換爲字節,只是一個在火車上快速編寫代碼的怪癖:)我已經更新了這個效果的例子,爲更好的例子做了...謝謝。 – 2010-11-10 20:39:19

+0

如何尷尬,對不起,我的意思是int不是char,那是什麼來一次做兩個編碼的答案,int在這個例子中當然是更好的給定的對象代表。 – 2010-11-10 20:49:40

0

你可以使用反序列化函數返回的對象類型,像這樣的例子:

public T DeSerializeFromString<T>(string data) 
     { 
      T result; 
      StringReader rdr = null; 
      try 
      { 
       rdr = new StringReader(data); 
       XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); 
       result = (T)xmlSerializer.Deserialize(rdr); 
      } 
      catch (Exception) 
      { 
       throw; 
      } 
      finally 
      { 
       rdr.Close(); 
      } 
      return result; 
     }