Page 1 of 1

Working with XML files in C#

#1 aj32  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 30
  • View blog
  • Posts: 577
  • Joined: 30-August 07

Post icon  Posted 12 April 2008 - 08:55 PM

*
POPULAR

Working With XML Files in C#



This is a basic tutorial which will show you how to write a C# program to work with XML files, we will be using the .NET module System.Xml.


For this tutorial, we will pretend we have been hired to create a program that will read xml files with specifications of your emplorer's computers. The XML files are structured like this:
<?xml version="1.0"?>
<CompSpecs>
  <CP>
    <Type>Dell Dimension 6600</Type>
    <RAM>2GBs</RAM>
    <CPU_Speed>2.8Ghz</CPU_Speed>
  </CP>
</CompSpecs>




To start, create a C# windows Forms Application, and create a form as shown below:

Posted Image

*Note: by default, the three textboxes should be named textBox1, textBox2, textBox3.

As you can see, we will load three items for each computer, Type, Amount of RAM, and the CPU Speed.
Now add an "open file dialog" to our project, to allow the user to open a "computer specifications xml file".

To get started, we will set up the loading part of our program, go into code view of Form1.h, and add the following using references:
using System.Xml;
using System.IO;



Reading and parsing xml content

To read and parse the xml file, we will:
  • Create a file stream
  • Create an XmlDocument that will read the filestream
  • Parse the XmlDocument
  • Display the InnerText of the Nodes with the needed information in it
First, go back into design mode, and double-click the "Load" Button, to create an onclick() event. In the newly created event, insert this code:

System.Windows.Forms.DialogResult OPEN = openFileDialog1.ShowDialog();
            if (OPEN == DialogResult.OK)
            {
                string path = openFileDialog1.FileName; // The Path to the .Xml file //
                FileStream READER = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //Set up the filestream (READER) //
                System.Xml.XmlDocument CompSpecs = new System.Xml.XmlDocument();// Set up the XmlDocument (CompSpecs) //
                CompSpecs.Load(READER); //Load the data from the file into the XmlDocument (CompSpecs) //
                System.Xml.XmlNodeList NodeList = CompSpecs.GetElementsByTagName("CompSpecs"); // Create a list of the nodes in the xml file //

                textBox1.Text = NodeList[0].FirstChild.ChildNodes[0].InnerText; // Load Type //
                textBox2.Text = NodeList[0].FirstChild.ChildNodes[1].InnerText; // Load RAM //
                textBox3.Text = NodeList[0].FirstChild.ChildNodes[2].InnerText; // Load CPU Speed //  
            }



We can now run our program and click the "Load" Button, the program should then load the above mentioned xml file, and output the data like this:

Posted Image



Now, that was simple enough wasn't it!


Changing and saving xml content

We will now need to create the Save function of our program. To edit and save the xml contents, we will:
  • Open a filestream
  • Load the contents of the filestream into an XmlDocument
  • Parse the XmlDocument
  • Edit the InnerText of the nodes that are being edited
  • Save the xmlDocument
To do this, create an "onclick()" event for our "Save" Button, and type in the code below in the newly created function:

if (openFileDialog1.FileName.Length > 0) //If a file is open
            {
                string path = openFileDialog1.FileName; // The Path to the .Xml file //
                FileStream READER = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //Set up the filestream (READER) //
                System.Xml.XmlDocument CompSpecs = new System.Xml.XmlDocument();// Set up the XmlDocument (CompSpecs) //
                CompSpecs.Load(READER); //Load the data from the file into the XmlDocument (CompSpecs) //


                System.Xml.XmlNodeList NodeList = CompSpecs.GetElementsByTagName("CompSpecs"); // Create a list of the nodes in the xml file //

                NodeList[0].FirstChild.ChildNodes[0].InnerText = textBox1.Text; // Save the type
                NodeList[0].FirstChild.ChildNodes[1].InnerText = textBox2.Text; // Save the RAM
                NodeList[0].FirstChild.ChildNodes[2].InnerText = textBox3.Text; // Save the CPU Speed

                //Save the xml file
                 //Create a FileStream for writing
                FileStream WRITER = new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite); //Set up the filestream (READER) //
                 //Write the data to the filestream
                CompSpecs.Save(WRITER);
            }



There we have it, the above code will allow us to change the xml file's attributes to match the ones the user has entered!


This is the end of this tutorial, I hope it was useful to you! Thanks for reading!
- AJ32 :)

I have finished writing part two of this XML tutorial: Working with xml files in C# - Part 2 :)

This post has been edited by aj32: 16 April 2008 - 06:58 PM


Is This A Good Question/Topic? 6
  • +

Replies To: Working with XML files in C#

#2 jousian  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 08-May 09

Posted 08 May 2009 - 05:53 AM

hi ,

I have tried to understand your code ,it's easy but I have a small problem in understanding this line

View Postaj32, on 12 Apr, 2008 - 07:55 PM, said:

Now add an "open file dialog" to our project, to allow the user to open a "computer specifications xml file".


can you explain it more furthur, please ?

Need your answer quickly beacuse I need a very similar code in a project that I will deliver to my teachers in a week

thank you
Was This Post Helpful? 0
  • +
  • -

#3 Bocard  Icon User is offline

  • D.I.C Head

Reputation: 15
  • View blog
  • Posts: 223
  • Joined: 24-September 08

Posted 12 May 2009 - 10:06 AM

View Postjousian, on 8 May, 2009 - 01:53 PM, said:

hi ,

I have tried to understand your code ,it's easy but I have a small problem in understanding this line

View Postaj32, on 12 Apr, 2008 - 07:55 PM, said:

Now add an "open file dialog" to our project, to allow the user to open a "computer specifications xml file".


can you explain it more furthur, please ?

Need your answer quickly beacuse I need a very similar code in a project that I will deliver to my teachers in a week

thank you


you just drag an open file dialog control from the toolbox onto your form
Was This Post Helpful? 0
  • +
  • -

#4 jousian  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 08-May 09

Posted 15 May 2009 - 03:46 AM

I want to know how to read several nodes in an Xml file

like this example :

<?xml version="1.0"?>
<CompSpecs>
  <CP1>
    <Type>Dell Dimension 6600</Type>
    <RAM>2GBs</RAM>
    <CPU_Speed>2.8Ghz</CPU_Speed>
  </CP1>
 <CP2>
    <Type>Dell Dimension 6600</Type>
    <RAM>2GBs</RAM>
    <CPU_Speed>2.8Ghz</CPU_Speed>
  </CP2>
</CompSpecs>


I knew about the (Nextsibling) method , it means the node beside the fisrt node

" NodeList[0].FirstChild.Nextsibling.ChildNodes[0].InnerText; " .. this line will get me the type in the cp2

but I don't want that .. I want to llop the file to get all the nodes of it without previously knowing how many nodes in the file

how could I do this ?

please help me quickly , me exams is two days to come .
Was This Post Helpful? 0
  • +
  • -

#5 Kuggi  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 5
  • View blog
  • Posts: 80
  • Joined: 16-January 09

Posted 10 July 2009 - 04:00 AM

Quote

To get started, we will set up the loading part of our program, go into code view of Form1.h, and add the following using references:


Hmm, Form1.h should be Form1.cs in C#.

But, nice short and clear tutorial.
Was This Post Helpful? 0
  • +
  • -

#6 prashant_kerkar  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 3
  • Joined: 17-July 09

Posted 17 July 2009 - 10:56 AM

I want to save changes i am making to xml file ....plz help

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace TestRad
{
    public partial class Form8 : Form
    {
        private XmlDocument xmlDoc;

        public Form8()
        {
            InitializeComponent();
        }

        private void Form8_Load(object sender, EventArgs e)
        {
            xmlDoc = new XmlDocument();
            LoadDocument();


            
        }


        private void LoadDocument()
        {
            try
            {
                // Load the XML data into it.     
                xmlDoc.Load("hosts.xml");

                // Initialize the TreeView control.
                tvTree.Nodes.Clear();
                tvTree.Nodes.Add(new TreeNode(xmlDoc.DocumentElement.Name));
                TreeNode tNode = new TreeNode();
                tNode = tvTree.Nodes[0];

                // Populate the TreeView with the DOM nodes.
                AddNode(xmlDoc.DocumentElement, tNode);
                tvTree.ExpandAll();
            }
            catch (XmlException xmlEx)
            {
                MessageBox.Show(xmlEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void AddNode(XmlNode xmlNode, TreeNode treeNode)
        {
            XmlNode xNode;
            TreeNode tNode;
            XmlNodeList xNodeList;
            int i;

            // Loop through the XML nodes until the leaf is reached.
            // Add the nodes to the TreeView during the looping process.
            if (xmlNode.HasChildNodes)
            {
                xNodeList = xmlNode.ChildNodes;
                for (i = 0; i <= xNodeList.Count - 1; i++)
                {
                    xNode = xmlNode.ChildNodes[i];
                    TreeNode newNode = new TreeNode(xNode.Name);

                    
                        treeNode.Nodes.Add(newNode);
                        tNode = treeNode.Nodes[i];

                        AddNode(xNode, tNode);
                    
                    
                }
            }
            else
            {
                // Here you need to pull the data from the XmlNode based on the
                // type of node, whether attribute values are required, and so forth.
                treeNode.Text = (xmlNode.OuterXml).Trim();
            }
        }

        private void tvTree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            //=e.Node.n
            if (e.Node.Nodes.Count == 0)
              textBox1.Text = e.Node.Text;
            else
                textBox1.Text = "";
            
                
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            tvTree.SelectedNode.Text = textBox1.Text;
            tvTree.Refresh();

            //TODO: Traverse the tree recursively and write the nodes to XML file; and reload the document
            
            //LoadDocument(); //remove comment from this to reload the document....
        }
    }
}


This post has been edited by macosxnerd101: 16 August 2010 - 11:06 AM
Reason for edit:: Added code tags

Was This Post Helpful? 1
  • +
  • -

#7 dccub83  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 07-August 09

Posted 12 August 2009 - 07:26 AM

View Postaj32, on 12 Apr, 2008 - 07:55 PM, said:

CompSpecs.Load(READER); //Load the data from the file into the XmlDocument (CompSpecs) //



Hey, this is a great little tutorial, exactly what I was looking for to help build an XML reader for a couple of Adobe forms that I've made in my office. The only trouble is with that particular line of code quoted above: it is giving me an error. it occurs once I test run the program, I'll click load and get the dialog box. I'll double-click my xml file and the following is the error it gives me:

XmlException was unhandled.
Data at the root level is invalid. Line 8, position 13.

If it helps, I'm using Microsoft Visual C# 2008 Express Edition. I'm also looking elsewhere for solutions, but as this is literally my first programming experience, I'm having trouble finding anything useful.
Was This Post Helpful? 0
  • +
  • -

#8 StickyTape  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 15-October 09

Posted 16 October 2009 - 02:03 AM

Superb uncluttered explanation.

It would be nice if you would add some code that adds a child element to a given element.

Thanks for an great explanation
Was This Post Helpful? 0
  • +
  • -

#9 Agent 1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 09-March 10

Posted 14 March 2010 - 02:10 AM

Hi dccub83

I was getting that same error, it you open the xml file in notepad you will see that for some reason "cs>" has been added to the <CompSpecs> endtag </CompSpecs>cs>, therefore the root element has been made invalid.

I dont know why this happens when you save the file sometimes, but if you delete the cs> off from the endtag then the program will work fine again.

Bizzare error but perhaps need to test for that and remove it in the load click event.

This post has been edited by Agent 1: 14 March 2010 - 02:13 AM

Was This Post Helpful? 0
  • +
  • -

#10 Tasman120  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 13-July 10

Posted 16 August 2010 - 10:20 AM

I'm not able to see the embedded images. Any trick?
Was This Post Helpful? 0
  • +
  • -

#11 OhScee  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 12-May 12

Posted 12 May 2012 - 09:56 AM

Not enough thanks for you, friend!
This is so very helpful~
Was This Post Helpful? 0
  • +
  • -

#12 florin08  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 03-December 12

Posted 03 December 2012 - 06:48 AM

Hy! First of all this is very helpful but unfortunately I can't see the pictures. Can you do something about it?
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1