XDocument xml 已解析但未能保存属性。 Xml.Linq

XDocument xml parsed but fails to save attributes. Xml.Linq

我正在遍历控件并在 xml 中设置文本框值,如下所示:

using System.Xml.Linq;

/* code */

XDocument _xml = XDocument.Load(_DialogOpen);

foreach (Control t in tableLayoutPanel.Controls)
{
    if (t is TextBox)
    {
        //setting the value
        _xml.Root.SetAttributeValue("isPreview", t.Text);
        //log
        textBox.AppendText("n=" + t.Name + " t=" + t.Text + Environment.NewLine);           
    }
}

_xml.Save(_DialogOpen);

我的问题是 _xml.Save(_DialogOpen); 确实保存了,但是 none 的属性被更改了,没有异常。如果有人有任何建议,将不胜感激。

xml 示例:

<?xml version="1.0" encoding="utf-8"?>
<config id="1">
  <parmVer __id="0" version="V1234" />
    <RecordSetChNo __id="0" isPreview="1" AIVolume="15" />
    <RecordSetChNo __id="1" isPreview="1" AIVolume="15" />
    <RecordSetChNo __id="2" isPreview="1" AIVolume="15" />
    <RecordSetChNo __id="3" isPreview="1" AIVolume="15" />
    <RecordSetChNo __id="4" isPreview="1" AIVolume="15" />
    <RecordSetChNo __id="5" isPreview="1" AIVolume="15" />
    <RecordSetChNo __id="6" isPreview="1" AIVolume="15" />
    <RecordSetChNo __id="7" isPreview="1" AIVolume="15" />
</config>

查看 OP

中的以下行
_xml.Root.SetAttributeValue("isPreview", t.Text);

上面的代码试图在根元素中设置属性,而您似乎想为元素 RecordSetChNo 设置它。

另外,相信你想设置基于每个文本框的属性,即每个文本框在xml中都有一个对应的属性。在这种情况下,您需要在设置属性之前过滤正确的 XElement(因为有多个 RecordSetChNo)。

    foreach (Control t in tableLayoutPanel.Controls)
    {
        if (t is TextBox)
        {
            //filter the xelement, only a sample here. 
            // Should change according to your requirement
            var filteredXElement = _xml.Root
                                      .Descendants("RecordSetChNo")
                                      .First(x=>x.Attribute("__id").Value==idToFilter);
            // Now set the attribute for the filtered Element
            filteredXElement.SetAttributeValue("isPreview", t.Text);
            //log
            textBox.AppendText("n=" + t.Name + " t=" + t.Text + Environment.NewLine);           
        }
    }