2013-11-20 99 views
0

我需要幫助瞭解如何doc.save工作。XmlDocument.Save不更新xml文件屬性

背景:獲得了一個從xml文檔獲取屬性的c#方法。然後,我將這些作爲Windows窗體中DataGridView的數據集發送。我試圖做到這一點,當用戶編輯表單的XML值得到更新。

首先我解析XML:Updater.cs

XmlNodeList elemList = doc.GetElementsByTagName("property"); 
for (int i = 0; i < elemList.Count; i++) 
{ 
    if (elemList[i].Attributes["value"] != null) 
    { 
     AppProperty property = new AppProperty(elemList[i].Attributes["name"].Value, elemList[i].Attributes["value"].Value); 
     properties.Add(property); 
    } 
} 

然後我把它發送到形式和更新表單數據集: Form1.cs中

private void Form1_Load(object sender, System.EventArgs e) 
{ 
    this.dataGridView1.SelectionMode = 
    DataGridViewSelectionMode.FullRowSelect; 
    this.dataGridView1.DataSource = properties; 
    this.dataGridView1.AutoGenerateColumns = false; 
} 

現在,當用戶編輯我觸發事件監聽器:Form.cs

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) 
{ 
    updater.updateSave(); 
} 

然後返回到我的updater cla ss和保存文件:Updater.cs

public void updateSave() 
{ 
    foreach (string f in filePaths) 
      doc.Save(f); 
} 

文件看起來像保存它,因爲它已經更新了「修改日期:」到我所使用的保存的時刻。我敢肯定,有一些參考價值混淆,但我不知道它

這些變化怎麼沒有被作出?

回答

1

你不改變XML文檔,你改變一個拷貝一些屬性

if (elemList[i].Attributes["value"] != null) 
{ 
    //You're making a copy of the attribute's value here: 
    AppProperty property = new AppProperty(elemList[i].Attributes["name"].Value, elemList[i].Attributes["value"].Value); 
    properties.Add(property); 
} 

GridView控件改變properties數據集,而這些變化不會傳播回XML文件。

+0

請注意,它們不會傳播,因爲它們根本與XmlDocument無關。 –

+0

所以會使用elemList [i] .Attributes [「名稱」]引用xml文檔? – Commanderson

+0

是的。您可以將此引用存儲在AppProperty對象中,並在保存文檔之前對其進行更新。 – Reda