繁体   English   中英

XDocument xml 已解析但无法保存属性。 xml文件

[英]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); 确实保存但没有更改任何属性,也不例外。 如果有人有任何建议,将不胜感激。

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);

上面的代码试图在 Root 元素中设置属性,但看起来您想为 Element 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);           
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM