2

我有一个如下的 xml:

<NewDataSet>
<Person>
    <FirstName>abc</FirstName>
    <LastName>xyz</LastName>
    <Address>12345abc</Address>
</Person>
<Person>
    <FirstName>abcd</FirstName>
    <LastName>pqr_xyz</LastName>
    <Address>1111abc</Address>
</Person>
<Person>
    <FirstName>abcde</FirstName>
    <LastName>ghy_xyz</LastName>
    <Address>98765abc</Address>
</Person>
</NewDataSet>

现在我想要这个 xml 到字典中。以下是我正在使用的代码。

 string data =
 @"<NewDataSet><Person>...";
 XDocument doc = XDocument.Parse(data); 
 Dictionary<string, string> dataDictionary = new Dictionary<string, string>();
 foreach (XElement elem in doc.Descendants("Person"))
    {
        var row = elem.Descendants();
        string str = elem.ToString();
        foreach (XElement element in row)
        {
           string keyName = element.Name.LocalName;
           dataDictionary.Add(keyName, element.Value);
        }
        yield return dataDictionary;
    }

现在这段代码不起作用。我知道某处有一个愚蠢的错误,有人可以帮我吗?这是将 xdocument 转换为 IEnumerable<Dictionary<string, object>>的一些类似要求的示例,但我也无法使其正常工作。

谢谢,

4

2 回答 2

3

You were trying to use the same instance of the dataDictionary object which threw the argument exception. An item with the same key has already been added. To correct this you need to initialize the dataDictionary within the first for each loop.

        Dictionary<string, string> dataDictionary = null;

        foreach (XElement elem in doc.Descendants("Person")) 
        { 
            var row = elem.Descendants(); 
            string str = elem.ToString();

            dataDictionary = new Dictionary<string, string>();

            foreach (XElement element in row) 
            { 
                string keyName = element.Name.LocalName; 
                dataDictionary.Add(keyName, element.Value); 
            } 

            yield return dataDictionary; 
        } 
于 2012-05-22T09:34:27.407 回答
0

您可以在循环时添加到列表中:

var list = new List<Dictionary<string, string>>();
foreach (XElement elem in doc.Descendants("Person"))
{
    var dataDictionary = new Dictionary<string,string>();
    var row = elem.Descendants();
    foreach (XElement element in row)
    {
       string keyName = element.Name.LocalName;
       dataDictionary.Add(keyName, element.Value);
    }
    list.Add(dataDictionary);
}
var enumDict = list.AsEnumerable();

我在这里假设您想要一个 Dictionary 对象列表,每个人都表示为字典。不过,重新阅读这个问题,我不确定这就是你所追求的......

于 2012-05-22T09:04:18.707 回答