以下代码目前正在运行,并将XML加载到类结构中。此结构由一组项(项)组成,每个项都具有静态属性,以及我用于可变数量属性的集合。
我想做的两件事: 1)我想将列表更改为具有唯一键的内容。我尝试了一本字典而且没有用,也许是HashSet ...导致...... 2)收集的关键应该由项目" id" XML属性。
我无法弄明白,并且尝试复制我用于项目变量参数的KVP模式不起作用。它将项目添加到"项目"但它们都是空的,并且没有填充集合的哈希值。
请帮助
[XmlRoot("ItemsContainer")]
public class Items
{
[XmlAttribute("Version")]
public string Version { get; set; }
[XmlArray("Items")]
[XmlArrayItem("Item")]
public List<Item> items = new List<Item>(); //TODO - The key in this collection should be unique and driven from an item's "Id" XML attribute
public static Items Load(string path)
{
var xml = Resources.Load<TextAsset>(path);
var serializer = new XmlSerializer(typeof (Items));
var reader = new StringReader(xml.text);
var items = (Items) serializer.Deserialize(reader);
reader.Close();
return items;
}
}
public class Item
{
//### Fixed Item Parameters
[XmlAttribute("Id")]
public int Id { get; set; }
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("Description")]
public string Description { get; set; }
[XmlElement("Value")]
public float Value { get; set; }
//### Variable Item Parameters as Key Value pairs.
[XmlArray("KVPS")]
[XmlArrayItem("KVP")]
public List<KeyValuePair<string, string>> KVPS { get; set; } //We will have cases were we don't want unique keys
}
[Serializable]
public class KVP<K, V>
{
public K Key { get; set; }
public V Value { get; set; }
public KVP()
{
}
public KVP(K key, V value)
{
Key = key;
Value = value;
}
}
这是关联的XML
<?xml version="1.0" encoding="utf-8"?>
<ItemsContainer Version="1.0">
<Items>
<Item Id="100">
<Name>Burger</Name>
<Description>The lovely tasting Big Mac</Description>
<Value>5.67</Value>
</Item>
<Item Id="101">
<Name>Sammich</Name>
<Description>Ham and cheese</Description>
<Value>2.80</Value>
</Item>
<Item Id="102">
<Name>Carling</Name>
<Description>Pint of carling</Description>
<Value>2.80</Value>
<KVPS>
<KVP>
<Key>alchohol</Key>
<Value>3.9</Value>
</KVP>
<KVP>
<Key>alchohol</Key>
<Value>4.9</Value>
</KVP>
<KVP>
<Key>alchohol</Key>
<Value>5.9</Value>
</KVP>
</KVPS>
</Item>
</Items>
</ItemsContainer>