[英]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.