如何使用列表(而不是数组)反序列化此xml
本文关键字:数组 反序列化 xml 何使用 列表 | 更新日期: 2023-09-27 18:09:04
我正在尝试使用c#在SILVERLIGHT中进行反序列化。在我使用XmlArray之前,它正在工作,但我想使用列表,而不是因为我已经使用列表完成了前面的部分(所以当我使用数组时看起来很奇怪)。
我的xml就像:
<ps>
<disable_others>
<disable_other>
<disable_value>1</disable_value>
<to_disable>skew</to_disable>
<to_disable>skew_side</to_disable>
</disable_other>
<disable_other>
<disable_value>0</disable_value>
<to_disable>automodel</to_disable>
</disable_other>
</disable_others>
<ps>
我的试着将它反序列化为:
[XmlRoot(ElementName = "ps")]
public class ps
{
[XmlArray("disable_others")]
[XmlArrayItem("disable_other", IsNullable = false)]
public List<string> Disable_Others { get; set; }
/* I know it can be done using the below but i have to use List not array:
[XmlArray("disable_others")]
[XmlArrayItem("disable_other", IsNullable = false)]
public Disable_Other[] Disable_Others { get; set; } */
}
[XmlRoot(ElementName = "disable_Others")]
public class Disable_Others
{
[XmlElement("disable_other")]
public List<Disable_Other> Disable_Other { get; set; }
}
[XmlRoot(ElementName = "Disable_Other")]
public class Disable_Other
{
[XmlElement("disablingitem")]
public int DisablingItem { get; set; }
[XmlElement("to_disable")]
public string[] To_Disable { get; set; }
[XmlElement("disable_value")]
public byte Disable_Value { get; set; }
}
有人可以帮助我实现使用列表而不是数组(XmlArray)的目标吗?
您的XML应该这样格式化:
<?xml version="1.0"?>
<ps xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<disable_others>
<Disable_Other>
<disablingitem>0</disablingitem>
<to_disable>
<string>skew</string>
<string>skew_side</string>
</to_disable>
<disable_value>1</disable_value>
</Disable_Other>
<Disable_Other>
<disablingitem>0</disablingitem>
<to_disable>
<string>automodel</string>
</to_disable>
<disable_value>0</disable_value>
</Disable_Other>
</disable_others>
</ps>
之后,你的类应该如下:
[Serializable]
[XmlRoot(ElementName = "ps")]
public class ps
{
[XmlArray("disable_others")]
[XmlArrayItem(typeof(Disable_Other), IsNullable = false)]
public List<Disable_Other> Disable_Others { get; set; }
public ps()
{
Disable_Others = new List<Disable_Other>();
}
}
[Serializable]
[XmlRoot("disable_other")]
public class Disable_Other
{
[XmlElement("disablingitem")]
public int DisablingItem { get; set; }
//[XmlElement("to_disable")]
[XmlArray("to_disable")]
public string[] To_Disable { get; set; }
[XmlElement("disable_value")]
public byte Disable_Value { get; set; }
}
在你的代码中像这样反序列化:
ps p;
XmlSerializer serializer = new XmlSerializer(typeof(ps));
using (StreamReader reader = new StreamReader("test1.xml"))
{
//basic exception handling...
try
{
p = (ps)serializer.Deserialize(reader);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}