【发布时间】:2016-04-23 22:50:33
【问题描述】:
我有一个正在使用的 XML 文档,我正在尝试将其反序列化为一个类。以下是我一直在使用的课程:
[Serializable()]
[XmlRoot("list")]
public class ItemRoot
{
public ItemRoot()
{
Items = new List<Item>();
}
[XmlElement("itemDefinition")]
public List<Item> Items { get; set; }
}
[Serializable()]
public class Item
{
[System.Xml.Serialization.XmlElement("id")]
public int Id { get; set; }
[System.Xml.Serialization.XmlElement("name")]
public string Name { get; set; }
[System.Xml.Serialization.XmlElement("examine")]
public string Examine { get; set; }
[System.Xml.Serialization.XmlElement("equipmentType")]
public string EquipmentType { get; set; }
[System.Xml.Serialization.XmlElement("noted")]
public bool Noted { get; set; }
[System.Xml.Serialization.XmlElement("noteable")]
public bool Noteable { get; set; }
[System.Xml.Serialization.XmlElement("stackable")]
public bool Stackable { get; set; }
[System.Xml.Serialization.XmlElement("parentId")]
public int ParentId { get; set; }
[System.Xml.Serialization.XmlElement("notedId")]
public int NotedId { get; set; }
[System.Xml.Serialization.XmlElement("members")]
public bool Members { get; set; }
[System.Xml.Serialization.XmlElement("specialStorePrice")]
public int SpecialStorePrice { get; set; }
[System.Xml.Serialization.XmlElement("generalStorePrice")]
public int GeneralStorePrice { get; set; }
[System.Xml.Serialization.XmlElement("highAlcValue")]
public int HighAlcValue { get; set; }
[System.Xml.Serialization.XmlElement("lowAlcValue")]
public int LowAlcValue { get; set; }
[System.Xml.Serialization.XmlElement("bonus")]
public List<int> Bonus { get; set; }
public override string ToString()
{
return $"[{Id}]{Name}";
}
}
这里是 XML 文件的简短摘录,其中包含数组中的一项(我使用的真实文件不止一项,只是为了清楚起见):
<list>
<itemDefinition>
<id>0</id>
<name>Stack Overflow</name>
<examine>Add coffee.</examine>
<equipmentType>NONE</equipmentType>
<noted>false</noted>
<noteable>false</noteable>
<stackable>false</stackable>
<parentId>-1</parentId>
<notedId>-1</notedId>
<members>true</members>
<specialStorePrice>0</specialStorePrice>
<generalStorePrice>0</generalStorePrice>
<highAlcValue>0</highAlcValue>
<lowAlcValue>0</lowAlcValue>
<bonus>
<int>0</int>
<int>0</int>
<int>0</int>
<int>0</int>
<int>0</int>
<int>0</int>
<int>0</int>
<int>0</int>
<int>0</int>
<int>0</int>
<int>0</int>
<int>0</int>
</bonus>
</itemDefinition>
这是我的反序列化方法:
XmlSerializer reader = new XmlSerializer(typeof(ItemRoot));
_file.Position = 0;
object file = reader.Deserialize(_file);
Root = (ItemRoot)file;
_file.Close();
我曾尝试调查similar 问题,但使用这些解决方案没有产生任何结果。
【问题讨论】:
-
我不确定我是否从您的问题中理解了您的问题。 根对象是一个数组只返回一个元素是什么意思?一个有效的 XML 文档必须只有一个根元素,请参阅 en.wikipedia.org/wiki/Root_element。您的 XML 不完整(例如,在 xmlvalidation.com 的验证失败)所以您能否编辑您的问题以给出您的问题的 complete example?