Remove a table from xml file using C#


Hi,

How can i remove a table from an xml file if the date is old using C#

This is how the xml file looks like:

<root>
<table>
<id> 0 </id>
<date> 20060404 </date>
</table>
<table>
<id> 1 </id>
<date> 20060822 </date>
</table>
<table>
<id> 2 </id>
<date> 20060904 </date>
</table>
</root>

What im trying to do is, removing a whole table if the date is old.

Comparing dates is not the issue, removing a table is.

Because if i remove it by name, it removes all the tables.

Can anyone help me with this issue

Thanks in advance!


Answer this question

Remove a table from xml file using C#

  • BrandonNC


    Hi,

    What if you just forget about the code i produced (because you find it too complicated), could you tell me your way how this can be done using DataSet

    That would be great!

  • Preston M. Price

    I'm a tad confused. The data you provioded hints that the <table> should actually be rows and the <date> and <id> should be columns. How many tables are in the DataSet and approximately how many rows are in each table and how many columns are in each table.

    Either way that code looks over complicated but I am not going to provide anything till I'm sure as to how the data is actually getting imported into the dataset so as to lessen confusion.



  • mohaccc

    You shouldn't iterate(foreach) through the collection while modifying it, so you can either use a for() loop that iterates through the count or rows in the table, or store a List of rows to delete and then delete them in a seperate loop.



  • belgie

    In your deletion loop, you don't want to remove them from the list. You want to delete them from the DataTable. I think the loop should look like:

    for (int i = 0; i < list.Count; i++ )
      {
            list[ i ].DeleteRow();
      }



  • oswldo


    Hi,

    You're right again (or should i say as usual).

    That worked.

    Thank you very much Todd!

  • Envitro

    I think Mark is right, you should change this code:

    if (difference.TotalDays > 29)
    {
    Console.WriteLine("table is outdated");
    xmlFile.Tables.Remove("table");
    }

    To be:

    if (difference.TotalDays > 29)
    {
    Console.WriteLine("table is outdated");
    dateRow.Delete(); // <table> element will be a row in Tables[0]
    }

    Since each "table" element will not show up as a DataTable, but as a DataRow in a DataTable.



  • Katherine


    Hi,

    You're right.

    Im using a list:

    List<DataRow> list = new List<DataRow>();

    Which is declared before the first foreach statement.

    In the foreach statement i add the rows which i want to delete to the list:

    list.Add(dateRow);

    And a for loop to delete them:

    for (int i = 0; i < list.Count; i++ )
    {
    list.Remove(i);
    }

    But the for statement gives me errors:

    The best overloaded method match for 'System.Collections.Generic.List<System.Data.DataRow>.Remove(System.Data.DataRow)' has some invalid arguments

    Argument '1': cannot convert from 'int' to 'System.Data.DataRow'

    What am i doing wrong



  • Brandon Teoh

    use
    XmlDocument TmpDoc = new XmlDocument();
    TmpDoc.Load(@"C:\pathtoxmlfile"); // what not.
    DateTime TmpDate = DateTime.Now.Date;
    String TmpQuery = "/root/table[date < '" + TmpDate.ToString("yyyyMMdd") + "']";
    XmlNodeList TmpNodes = TmpDoc.SelectNodes(TmpQuery);
    for (Int32 i=0; i<TmpNodes.Count; i++)
    {
    TmpNodesIdea.ParentNode.RemoveChild(TmpNodesIdea); // removes it by getting the parent and removing itself.
    }
    // Save or what not
    The only thing that should be noted is that your data has a space before and after every value. This may mess the above xpath query up. If that space is actually there then put a space after the first single quote and before the last single quote so that the xpath query string value that it compares to has the same spaces. either that or ditch the spaces in the xml

    Hope this helps.


  • Israel Alpert


    Those rows, columns and tables kinda confused me.

    I don't know what is what anymore.

    But i tried the method dateRow.Delete();

    It gave me this error in the console:

    Collection was modified; enumeration operation might not execute.

    I know why i got this error, because im trying to modify the xml file while im iterating it within the foreach statement.

    How can i iterate it and still be able to delete

    Because there might be more dates that are outdated i want to delete.

    Btw Todd, thanks for your reply!

  • Greg Cadmes


    Hi,

    Thank you for your reply!

    But can this also be done with DataSet

    Coz i've used DataSet.

    This is the code i have:

    static void Main(string[] args)
            {
                try
                {
                    DataSet xmlFile = new DataSet();
                    xmlFile.ReadXml("test.xml");
                    DataTable tables = new DataTable(xmlFile.Tables.ToString());
                    int index = xmlFile.Tables.IndexOf(tables.ToString());
                   
                    //for(int i=0; i <
                    Console.WriteLine(index.ToString());

                    if ( xmlFile != null)
                    {
                        if (tables.Contains("table"))
                        {
                            //System.Diagnostics.Debug.WriteLine(tables.IndexOf("table"));
                            Console.WriteLine(tables.IndexOf("table"));
                        }
                    }
                   
                    foreach (DataRow dateRow in xmlFile.Tables[0].Rows)
                    {
                        string date = dateRow["Date"].ToString();
                        DataRow[] tempXmlFileRows = xmlFile.Tables[0].Select("Date = " + date);

                        DateTime dateNow = DateTime.Now;
                        dateNow.ToString("yyyyMMdd");
                        Console.WriteLine("The date of today = " + dateNow.ToString("yyyyMMdd"));

                        date = date.Trim();
                        DateTime dateXmlFile = DateTime.ParseExact(date, "yyyyMMdd",
                                System.Globalization.DateTimeFormatInfo.InvariantInfo);

                        TimeSpan difference = dateNow.Subtract(dateXmlFile);

                        if (tempXmlFileRows.Length != 0)
                        {
                            Console.WriteLine("The date in xmlfile = " + dateXmlFile);
                            Console.WriteLine("Difference = " + difference);

                            if (difference.TotalDays > 29)
                            {
                                Console.WriteLine("table is outdated");
                               
                                xmlFile.Tables.Remove("table");

                            }

                            else
                            {
                                Console.WriteLine("table is NOTTTTT outdated");
                            }
                           
                          xmlFile.AcceptChanges();
                        }
                    }
                  xmlFile.WriteXml("test.xml");
                }

                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
               
                Console.Read();



    How can i change this code to do the same MarcD

    Thanks in advance!


  • Remove a table from xml file using C#