2012-12-05 151 views
0

更新多個XElements我有一個看起來像這樣的XML文件:在foreach循環

<Contacts> 
    <Person name="James" id"=1" /> 
    <Person name="Edward" id"=2" /> 
</Contacts> 

我想要做的事,所以如果ID = 2,創建10種以上的人,並更新自己的ID和名稱,這樣:

if (person.ID == 2) 
{ 
    foreach (var item in duplicatePersons) 
    { 
     pers.SetAttributeValue("id", item.Key); 
     pers.SetAttributeValue("name", item.Value); 
     allPersons.Add(pers); 
    } 
} 

duplicatePersons是一個字典,其中包含所有重複的人。

的問題是,這個foreach循環的第一次迭代產生:

<Person name="Josh" id"=3" /> 

在第二次迭代之後,它應該看起來像:

<Person name="Josh" id"=3" /> 
<Person name="Jacob" id"=4" /> 

但它看起來像:

<Person name="Jacob" id"=4" /> 
<Person name="Jacob" id"=4" /> 

所以第二次迭代更新第一個和第二個元素。

任何想法,爲什麼?

回答

1

您將所有屬性設置爲同一對象實例pers。您應該在循環中創建一個新的Person對象

foreach (var item in duplicatePersons) 
{ 
    Person pers = new Person(); 
    pers.SetAttributeValue("id", item.Key); 
    pers.SetAttributeValue("name", item.Value); 
    allPersons.Add(pers); 
}