Link to home
Start Free TrialLog in
Avatar of Martin Davis
Martin DavisFlag for United States of America

asked on

Creating XML file in Winforms to Load into a DataGrid in C# part 1

I need to write a function in C# that checks if an XML file exists at a certain path. If the file exists I need to append child nodes(person) to the XML file and save it.  If it doesn't exists, I need to create The XML file , then append the child nodes(person) to this and save it.  I will later load the XML file using another form that contains a DataGrid so the file can be viewed in a grid style layout.  How would I write a function to do this? The part 2 of this question I will put in a separate question as far as loading the DataGrid. After a solution is found to this one. Thanks for any help in advance.
<Family> // root 
<person>
<firstname>Danny</firstname>
<lastname>Glover</lastname>
<address> 542 bell south</address>
</person>
<person>
<firstname>Brad</firstname>
<lastname>Smith</lastname>
<address> 508 bell south</address>
</person>
</Family>

Open in new window

Avatar of williamcampbell
williamcampbell
Flag of United States of America image

Something like...          


            XmlDataDocument doc;
            doc = new XmlDataDocument();
           bool exists = true;
            try
            {
                doc.Load("C:/Work//test12.xml");
            }
            catch (System.IO.FileNotFoundException fe)
            {
                // File not found
                exists = false;
                doc.CreateElement( "Family" );
            }
            
            XmlDocument doc2 = new XmlDocument();
            doc2.LoadXml( "<person......");
 
            doc.AddChild ( doc2.DocumentElement );
 
           doc.Save ();
            

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Dmitry G
Dmitry G
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I tested the code and it works. However it does not validates the xml. If xml is not valid - we'll get an error. So some additional precautions should be taken. E.g. put doc.Load(filename)  into try-catch
Bonus :)

Really, I probably can give you a solution to part 2. The easiest way to display your xml in a grid is to use a dataset. If you want to just display (not edit) - set e.g. datagridview1.editmode = editprogrammatically
        private void button1_Click(object sender, EventArgs e)
        {
            string filename = "family.xml";
            DataSet ds = new DataSet();
            ds.ReadXml(filename);
            this.dataGridView1.DataSource = ds.Tables[0];
        }

Open in new window

Avatar of Martin Davis

ASKER

Thanks so much this work like a charm and saved me a lot of time. P. S Thanks for the bonus.