简体   繁体   English

具有多个值的相同键的表单字典解析xml

[英]form dictionary with same key for multiple values parse the xml

MY xml format is this 我的xml格式是这个

<?xml version='1.0' encoding='us-ascii'?> 
<root>
<key value="22.wav">
<Index>18</Index>
</key>
<key value="EFG.wav">
<Index>5</Index>
<Index>14</Index>
</key>
</root>

How Do i form dictionary? 我如何形成字典?

Here is a how you parse the xml file and populate a dictionary 这是解析xml文件并填充字典的方式

Dictionary<string, int[]> keyIndexCollection = new Dictionary<string, int[]>();
XmlDocument doc = new XmlDocument();
doc.Load("input.xml");
XmlNodeList keyNodeList = doc.SelectNodes("root/key");
List<int> indexValues = new List<int>();
foreach (XmlNode node in keyNodeList)
{
    XmlNodeList indexNodeList = node.SelectNodes("Index");
    int parsedIndex;
    indexValues.Clear();
    foreach (XmlNode indexNode in indexNodeList)
    {
        if (int.TryParse(indexNode.InnerText, out parsedIndex))
        {
            indexValues.Add(parsedIndex);
        }
    }

    keyIndexCollection.Add(node.Attributes["value"].Value, indexValues.ToArray());
}

and here is a sample code for iterating the dictionary 这是迭代字典的示例代码

foreach (string key in keyIndexCollection.Keys)
{
    int[] values = keyIndexCollection[key];

    Console.WriteLine("Key = " + key);
    foreach (int value in values)
    {
        Console.WriteLine("\tValue = " + value);
    }
}

You can do it this way : 您可以这样操作:

var doc = XDocument.Load("path_to_xml_file.xml");
Dictionary<string, int[]> dictionary = new Dictionary<string, int[]>();
foreach (var key in doc.Root.Elements("key"))
{
    dictionary.Add((string)key.Attribute("value"), key.Elements("Index").Select(o => int.Parse((string)o)).ToArray());
}

Or simplified using .ToDictionary() extension method : 或使用.ToDictionary()扩展方法简化:

var dict = doc.Root
              .Elements("key")
              .ToDictionary(o => (string) o,
                            p => p.Elements("Index").Select(o => int.Parse((string) o)).ToArray());

If you load your XML like this: 如果您这样加载XML:

var xd = XDocument.Load("path_to_xml_file.xml");

Then you can create two different dictionaries like this: 然后,您可以创建两个不同的字典,如下所示:

var dict1 = 
    xd
        .Document
        .Root
        .Elements("key")
        .ToDictionary(
            x => x.Attribute("value").Value,
            x => x.Elements("Index")
                .Select(y => y.Value)
                .ToArray());


    var dict2 = 
    xd
        .Document
        .Root
        .Elements("key")
        .SelectMany(x => x
            .Elements("Index")
            .Select(y => new { x = x.Attribute("value").Value, y = y.Value }))
        .ToDictionary(x => x.y, x => x.x);

And these results look like this: 这些结果如下所示:

结果

I suspect you want the first one. 我怀疑你想要第一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM