【问题标题】:XmlDocument.Save not updating xml file propertiesXmlDocument.Save 不更新 xml 文件属性
【发布时间】:2013-11-20 15:36:41
【问题描述】:

我需要帮助了解 doc.save 的工作原理。

背景:得到了一个从 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.cs

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

该文件看起来像是已保存,因为它已将“修改日期:”更新到我使用保存的那一刻。我确定有一些参考值混淆,但我无法弄清楚

为什么没有做出改变?

【问题讨论】:

    标签: c# xml datagridview xmldocument


    【解决方案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 文档。

    【讨论】:

    • 请注意,它们不会被传播,因为它们根本与 XmlDocument 无关。
    • 那么使用 elemList[i].Attributes["name"] 会引用 xml 文档吗?
    • 是的。您可以将此引用存储在AppProperty 对象中并在保存文档之前对其进行更新。
    猜你喜欢
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-04
    • 1970-01-01
    相关资源
    最近更新 更多