我有以下格式的xml:
<select>
<option value="2" ID="451">Some other text</option>
<option value="5" ID="005">Some other text</option>
<option value="6" ID="454">Some other text</option>
<option value="15" ID="015">Some other text</option>
<option value="17" ID="47">Some other text</option>
</select>
我还有一个字典,它有一个键值,我希望与上面xml中相关选项的ID匹配,并返回字典值。我不知道如何完成这个。
我正在考虑像这样循环字典:
foreach (KeyValuePair<string, string> dictionaryEntry in dictionary)
{
if (dictionaryEntry.Key == "AttributeValue")
{
//do stuff here
}
}
但我不确定如何比较? 谢谢
答案 0 :(得分:0)
这样的事情应该有效:
class Program
{
static void Main(string[] args)
{
String xmlString = @"<select>
<option value=""2"" ID=""451"">Some other text</option>
<option value=""5"" ID=""005"">Some other text</option>
<option value=""6"" ID=""454"">Some other text</option>
<option value=""15"" ID=""015"">Some other text</option>
<option value=""17"" ID=""47"">Some other text</option>
</select>";
Dictionary<string, string> theDict = new Dictionary<string, string>();
theDict.Add("451", "Dict Val 1");
theDict.Add("005", "Dict Val 2");
theDict.Add("454", "Dict Val 3");
theDict.Add("015", "Dict Val 4");
theDict.Add("47", "Dict Val 5");
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
XmlWriterSettings ws = new XmlWriterSettings();
ws.Indent = true;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (reader.Name == "option")
{
System.Diagnostics.Debug.WriteLine(String.Format("ID: {0} \nValue: {1} \nDictValue: {2}", reader.GetAttribute("ID"), reader.GetAttribute("value"), theDict[reader.GetAttribute("ID")]));
}
break;
}
}
}
}
}
我不太确定你提到的字典中有什么,但我的猜测是你总共有三个不同的值,xml中的“value”,xml中的ID,以及字典和键中的另一个值在字典中是xml中的ID。假设所有这些都是正确的,那么这将从xml中获得所需的内容。
答案 1 :(得分:0)
您可以从xml&amp;中创建一个字典。然后根据密钥获取值。
例如
XDocument doc1 = XDocument.Load(XmlFileName);
var elements1 = (from items in doc1.Elements("select").Elements("option")
select items).ToDictionary(x => x.Attribute("ID").Value, x => x.Attribute("value").Value);