简体   繁体   中英

Can't update Xml file

I'm trying to update my xml file using this code.

int i;
XmlNodeList list = xdoc.SelectNodes("Sale/SalesLines/SalesLine");

foreach (XmlNode node in list)
{
    for (i = 0; i < count; i++)
    {
        node.SelectSingleNode("VatAmount").InnerText = Convert.ToString(datagridview.Rows[i].Cells[10].Value);
        xdoc.Save(path);
    }                    
}

So first of all I'm trying to update the xml file using the integer data from my grid. Now there are 2 salesline nodes in my xml file. The above code does update the values in that node but its sets both the elements value as the last element that was read using the loop. It reads both(there are 2 values read and updated in the file) the values but updates only the last read value in both those nodes vatamount element. Btw count holds the count of rows in the grid. Can anyone help me fix this. I really need this solved.

Ok. Guys Please forgive me. My co-employee saw my code and he said not to use that code but to use this.

DevExpress.XtraGrid.Views.Grid.GridView view = (DevExpress.XtraGrid.Views.Grid.GridView)gridControl1.FocusedView;
view.PostEditor();
view.RefreshData();

DataTable table = ((DataView)gridView1.DataSource).ToTable();
foreach (DataRow dr in table.Rows)
{
    //textBox8.Text += Convert.ToString(dr["NewVATAmt"]);
    foreach (XmlNode node in list)
    {
        node.SelectSingleNode("VatAmount").InnerText = Convert.ToString(dr["NewVATAmt"]);
    }    
}
xdoc.Save(path);

So I'm now using a dev express grid control instead of a datagrid. And with this code i'm facing the same problem. Please go through this code ad try to suggest a fix. Please.

If I understand correctly what you want then you need to keep a counter out of the foreach loop (not a loop inside a loop). Something like this (notice that you should still check if Rows[i] exists or you get an exception).

int i = 0;
foreach (XmlNode node in list)
{
   node.SelectSingleNode("VatAmount").InnerText = Convert.ToString(datagridview.Rows[i].Cells[10].Value);
   i++;
}

xdoc.Save(path);

Also, you probably want to save the document only once after you updated all the nodes.

UPDATE: for the second sample you should follow a similar pattern.

DataTable table = ((DataView)gridView1.DataSource).ToTable();
int i = 0;
foreach (XmlNode node in list)
{
    node.SelectSingleNode("VatAmount").InnerText = Convert.ToString(table.Rows[i]["NewVATAmt"]);
    i++;    
}
xdoc.Save(path);

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