我正在使用 silverlight 来实现 xml 的反序列化,如下所示:
字符串 xmlString=
<attributes>
<value>1</value>
<showstatus>yes</showstatus>
<disableothers>
<disableother>
<disablevalue>1</disablevalue>
<todisable>skew</todisable>
<todisable>skew_side</todisable>
</disableother>
<disableother>
<disablevalue>0</disablevalue>
<todisable>automodel</todisable>
</disableother>
</disableothers>
</attributes>
在我试图实现这一目标的过程中,我觉得我在课堂上有所收获。班级如下:
[XmlRoot(ElementName = "attributes")]
public class Attributes
{
[XmlElement("disableOthers")]
public List<DisableOthers> DisableOthers { get; set; }
}
[XmlRoot(ElementName = "disableOthers")]
public class DisableOthers
{
[XmlElement("disableOthers")]
public List<DisableOther> 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();
}
Output:
{
Value: 1,
ShowStatus: "yes",
DisableOthers: [
{
DisableValue: 1,
ToDisable: [ "skew", "skew_side" ]
},
{
DisableValue: 0,
ToDisable: [ "automodel" ]
}
]
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)