Xml序列化c#

问题描述:

无法理解我做错了什么,结果集是空的。
我的代码: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> 

移动[XmlElement]属性的属性。
XmlSerializer忽略私有成员。

为SLaks说

还贵点对象同时显示领域的bool尚未值在XML文件中的整数至少为(21,3,5,7等)

布尔变量可以是true或false,其整数值为1和0.因此,您的XML具有无效数据和/或您的类属性类型错误。

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

而在你的观点中,x和y都不应该是bools。

解决方案:

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

你可以使用反序列化函数返回的对象类型,像这样的例子:

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; 
     }