简体   繁体   中英

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

I am looping over the controls and setting the textbox values in the xml like so:

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

My problem is that the _xml.Save(_DialogOpen); does save but none of the attributes are changed and there is no exception. If anyone has any suggestions it will be greatly appreciated.

xml example:

<?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>

Take a look at the following line from OP

_xml.Root.SetAttributeValue("isPreview", t.Text);

The above code is attempting to set the attribute in Root element, when it looks like you want to set it for the Element RecordSetChNo .

Also, believe you want to set the attribute based on each of the textboxes, ie, each textbox has a corresponding attribute in the xml. In such a scenario, you would need to filter the right XElement (since there are more than one RecordSetChNo ) before setting the attribute.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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