如何在c#对象中反序列化这个嵌套的xml

我使用silverlight ot实现xml的反序列化,如下所示:

String xmlString =

 1 yes   1 skew skew_side   0 automodel    

在我尝试实现这一点时,我觉得我在课堂上有一些东西。 课程如下:

  [XmlRoot(ElementName = "attributes")] public class Attributes { [XmlElement("disableOthers")] public List DisableOthers { get; set; } } [XmlRoot(ElementName = "disableOthers")] public class DisableOthers { [XmlElement("disableOthers")] public List DisableOther { get; set; } } [XmlRoot(ElementName = "disableOther")] public class DisableOther { [XmlElement("disablingitem")] public int DisablingItem { get; set; } [XmlElement("todisable")] public int ToDisable { get; set; } [XmlElement("disablevalue")] public int DisableValue { get; set; } } 

如果我的课程对应于给定的xml,那么有人可以纠正我吗? 会是一个很大的帮助。

注意:问题确切的是当我创建父类的对象然后它给出“0”值。 我已经尝试过了,然后我来到stackoverflow。

您不需要DisableOthers类。 只需使用带有XmlArrayItem属性的属性:

 [XmlArrayItem("disableother", IsNullable=false)] [XmlArray("disableOthers")] public DisableOther[] DisableOthers { get; set; } 

完整映射看起来像:

 [XmlRoot("attributes")] public class Attributes { [XmlElement("value")] public byte Value { get; set; } [XmlElement("showstatus")] public string ShowStatus { get; set; } [XmlArray("disableothers")] [XmlArrayItem("disableother", IsNullable = false)] public DisableOther[] DisableOthers { get; set; } } [XmlRoot("disableOther")] public class DisableOther { [XmlElement("disablevalue")] public byte DisableValue { get; set; } [XmlElement("todisable")] public string[] ToDisable { get; set; } } 

反序列化:

 XmlSerializer serializer = new XmlSerializer(typeof(Attributes)); using (var reader = new StringReader(xmlString)) { var attributes = (Attributes)serializer.Deserialize(reader); attributes.Dump(); } 

输出:

 { Value: 1, ShowStatus: "yes", DisableOthers: [ { DisableValue: 1, ToDisable: [ "skew", "skew_side" ] }, { DisableValue: 0, ToDisable: [ "automodel" ] } ] } 

/ *如果你想从xml到c#代码读取对象

 1st create your xml file 2nd your c# code to DeSerializer 

* /

 //if you want read objects from xml to c# code //1st create your xml file     1   2  1    3   4  2   //2nd your c# code to DeSerializer public List FieldCollections; public SelftestAdv2() { XmlSerializer xs = new XmlSerializer(typeof(List), new XmlRootAttribute("FieldConfiguration")); using (var streamReader = new StreamReader("fff.xml")) { FieldCollections = (List)xs.Deserialize(streamReader); } } 

//如果你想要相反,你有对象要保存在xml中

  public SelftestAdv2(int x) { B b1 = new B(); b1.v = 3; B b2 = new B(); b2.v = 4; B b3 = new B(); b3.v = 5; B b4 = new B(); b4.v = 6; A a1 = new A();a1.id = 1; a1.b.Add(b1); a1.b.Add(b2); A a2 = new A();a2.id = 2; a2.b.Add(b3); a2.b.Add(b4); List listA = new List(); listA.Add(a1); listA.Add(a2); XmlSerializer xs = new XmlSerializer(typeof(List), new XmlRootAttribute("FieldConfiguration")); using (var streamReader = new StreamWriter("fff.xml")) { xs.Serialize(streamReader,listA); } } `