- Home /
An element with the same key already exists in the dictionary
I was testing an inventory system and ...
=-=-=
ArgumentException: An element with the same key already exists in the dictionary. System.Collections.Generic.Dictionary`2[System.String,System.String].Add (System.String key, System.String value) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:404) RPGItemDatabaseScript.ReadItemsFromDatabase () (at Assets/scripts/Items/RPGItemDatabaseScript.cs:40) RPGItemDatabaseScript.Awake () (at Assets/scripts/Items/RPGItemDatabaseScript.cs:17)
=-=-=
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Xml;
using System.IO;
public class RPGItemDatabaseScript : MonoBehaviour {
public TextAsset itemInventory;
public static List<BaseItem> inventoryItem = new List<BaseItem> ();
private List<Dictionary<string, string>> inventoryItemsDictionary = new List<Dictionary<string, string>>();
private Dictionary<string, string> inventoryDictionary;
void Awake(){
ReadItemsFromDatabase ();
for (int i = 0; i < inventoryItemsDictionary.Count; i++) {
inventoryItem.Add (new BaseItem (inventoryItemsDictionary [i]));
}
}
public void ReadItemsFromDatabase(){
XmlDocument xmlDocument = new XmlDocument ();
xmlDocument.LoadXml (itemInventory.text);
XmlNodeList itemList = xmlDocument.GetElementsByTagName ("Item");
foreach (XmlNode itemInfo in itemList) {
XmlNodeList itemContent = itemInfo.ChildNodes;
inventoryDictionary = new Dictionary<string, string>();
foreach (XmlNode content in itemContent) {
inventoryDictionary.Add(content.Name.ToString(), content.InnerText);
inventoryItemsDictionary.Add (inventoryDictionary);
}
}
}
}
=-=-=-=
Xml file
<Item>
<ItemName>TestItem</ItemName>
<ItemID>1</ItemID>
<ItemTypes>WEAPON</ItemTypes>
<ItemName>TestItem2</ItemName>
<ItemID>2</ItemID>
<ItemTypes>WEAPON</ItemTypes>
</Item>
=-=-=
I already researched in some places, but all I found was answers saying to remove certain specific code, and did not explain right what caused the error.
Have you tried using Debug.Log to print the actual string that is to be added to teh dictionary as a key?
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Runtime instantiation based on XML 1 Answer
Create List of Dictionaries C# 2 Answers
[JS] String,List dictionary doesn't compile. Any suggestions? 1 Answer