WinForms+C#中DataGridView编辑XML节点多属性后保存失效问题求助
WinForms+C#中DataGridView编辑XML节点多属性后保存失效问题求助
各位大佬好,我最近在做一个WinForms+C#项目,遇到了一个棘手的问题:用DataGridView编辑XML中的节点属性后,保存时同一个节点的多个修改只能生效一个,其他的都没被更新,想请大家帮忙看看哪里出问题了!
先说说我的场景:我读取了一个10万行以上的XML文件,把内容展示在多标签页的DataGridView里,读取和展示都很顺利,但编辑保存的时候掉链子了——如果我对同一个<EUParameter>节点修改多个属性,然后切换到其他节点编辑,最后点击保存时,同一个节点里只有第一个修改能成功写入XML,剩下的修改都没生效。
我的XML节点结构大概是这样的:
<EUParameters> <EUParameter FtirKey="1" Ftir="2" TimeSource="3" Trigger="" Algorithm="" Calibration_ID="4" Effective="5" Verified="1/1/1900 12:00:00 AM" MetStat="5" SignConvention="" Type="6" Op="7" Description="example" Units="numbers" ID="example"> <Polynomial Set="" Degree="" /> <Sources /> <Arguments /> <Expression></Expression> <Syllables> <Syllable LSB="" MSB="" Word="" WordInc="" Frame="" FrameInc="" Number="" /> </Syllables> </EUParameter> <!-- 几千个类似的EUParameter节点 --> </EUParameters>
我现在的处理逻辑是用一个CellEdit类记录每个编辑过的单元格信息,点击保存按钮时遍历这个列表去更新XML,相关代码如下:
private void save_Click(object sender, EventArgs e) { SaveChanges(); } private void SaveChanges() { // Update the XML file with the modified values UpdateXmlFile(); MessageBox.Show("Changes saved successfully."); // Clear the list of edited cells after saving editedCells.Clear(); } private void UpdateXmlFile() { // Load the XML file XDocument xmlDocument = XDocument.Load(filePath); int euParameterIndex = 0; // Counter to keep track of EUParameter index foreach (CellEdit cellEdit in editedCells) { string attribute = cellEdit.Attribute; string label = cellEdit.Label; // Find the EUParameter node based on its index in the XML structure XElement euParameterNode = xmlDocument.Descendants("EUParameter") .ElementAtOrDefault(euParameterIndex); if (euParameterNode != null) { // Update the attribute value XAttribute attributeElement = euParameterNode.Attribute(attribute); if (attributeElement != null) { attributeElement.Value = label; } } euParameterIndex++; // Increment the EUParameter index for the next iteration } // Save the updated XML file xmlDocument.Save(filePath); } private bool IsAttributeValid(string attributeValue) { string[] validAttributes = { "ID", "Description", "Units", "FtirKey", "Ftir", "TimeSource", "Trigger", "Algorithm", "Calibration_ID", "Effective", "Verified", "MetStat", "SignConvention", "Type", "Op" }; return validAttributes.Contains(attributeValue); } private class CellEdit { public int EUParameterCount { get; } public int ColumnIndex { get; } public string Attribute { get; } public string Label { get; } public CellEdit(int euParameterCount, int columnIndex, string attribute, string label) { EUParameterCount = euParameterCount; ColumnIndex = columnIndex; Attribute = attribute; Label = label; } }
我现在的需求是:不管是对同一个<EUParameter>节点修改多个属性,还是对多个不同节点修改属性,点击保存后所有的修改都能正确写入XML文件。但目前的逻辑明显有问题,同一个节点的多属性修改只能保存第一个,实在找不到问题所在,恳请各位大佬指点迷津!
备注:内容来源于stack exchange,提问作者Jamil Matin
相关产品推荐
相关产品推荐

