如何在Silverlight中反序列化此xml

时间:2010-07-08 11:01:24

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

Xml在这里

<?xml version="1.0" encoding="utf-8"?>
<s>
  <Items>
  <b name="test" width="100">
     <Items>
       <d x="1"/>
       <e width="50"/>
     </Items>
  </b>
  <b name="test2" width="200">
     <Items>
       <d x="2"/>
     </Items>
  </b>
  </Items>
</s>

我正在创建这些类

public class s
{
  public s(){
  Items=new List<b>();
  }
  List<b> Items{get;set;}
}

public class b
{
  public b(){
  Item=new List<object>();
  }
  [XmlAttribute]
  public string name {get;set;}
  [XmlAttribute]
  public int width {get;set;}
}

public class d
{
  public d(){}
  [XmlAttribute]
  public int x {get;set;}
}

public class e
{
  public e(){}
  [XmlAttribute]
  public int width {get;set;}
}

我的主要代码在这里

s mainobj=null;
XmlSerializer ser=new XmlSerializer(typeof(s));
mainobj=ser.Deserialize(memoryStream) as s;

Debug.WriteLine(mainobj.Items.Count.ToString());
Debug.WriteLine(mainobj.Items[0].name);
Debug.WriteLine(mainobj.Items[0].Items.Count.ToString());

输出

2
test
0

b个对象项包含2种对象。

如何反序列化此对象。

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:1)

我最喜欢理解这些反序列化问题的方法是向后测试它。

使用XmlSerializer将期望类的实例SERIALIZE到XML文件,并查看生成的XML。这应该会给你一些好的线索,帮助你了解正在发生的事情......