0

我有一些以下格式的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

            }
        }

但我不确定如何比较?谢谢

4

2 回答 2

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;
                }

            }
        }
    }
}

我不太确定你提到的字典中有什么,但我猜你总共有 3 个不同的值,xml 中的“值”,xml 中的 ID,字典中的另一个值和字典中的键是 xml 中的 ID。假设所有这些都是正确的,那么这将从你的 xml 中得到你需要的东西。

于 2013-05-03T16:19:40.260 回答
0

您可以从您的 xml 创建一个字典,然后根据键获取值。

例如。

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);
于 2013-05-03T16:19:42.277 回答