Saturday, January 30, 2010

An XML File Editor in C#

Merely a week had passed from my first post "A Recursive XML Parser in C#" that I was asked to create an XML editor in a Windows Forms application.

My first thoughts were to modify the code I wrote for the parser and get it going in less than an hour. So late on a Friday afternoon, I started working on my ingenious idea. Four hours later I was still struggling. Absolutely outraged and frustrated, I decided to throw away the code change idea and go back to the drawing board so-to-speak. The result of this approach was simply incredible.

Before I explain my new approach, I must emphasis a great lesson in development: If you are struggling to achieve a standard operation (like editing an XML file, or logging, etc), you are most certainly using the wrong tools.

Writing to an XML File

In order to demonstrate this technique, a Windows Forms Application similar to the screen shot below is created.

(Fig 1)

The "Browse" button, displays a file open dialog box that helps the user to navigate his/her computer/network file system for a given xml file.

(Fig 2)

Once the user selects the xml file and clicks the "Open" button, the content of the xml are read and displayed in a Windows Forms DataGrid control as shown in Figure 1 above.
Clicking on the small '+' sign in the left-hand margin will expand the node and reveals the small navigation bar on the right-hand side of the grid title. The "Arrow" button is the "Back" button while the other button to right of the arrow button is help to hide or reveal the parent nodes of the displayed node. Finally you can change any string of any nodes and click the "Save" to persist the changes.

The Program:

The solution is embarrassingly simple. There only 4 steps as follows:

  • Create a DataSet.
  • Populate it by calling its ReadXml method passing the XML file path to it.
  • Set it as the DataSource of a DataGrid control.
  • To persist the changes to file, get the DataSet of the dataGrid and call its WriteXml method.
The GetXmlDataSet reads the XML file contents into a DataSet and is defined as below:



As mentioned before we simply instantiate a DataSet and call its ReadXml mehtod, passing the name of the XML file.

SaveXmlDataSet does just the opposite, Saving the modified DataSet to the file.



Before diving in to the complete code, I'd like to make two points: Firsltly, I prefer to use FileInfo class as opposed to the FILE class (with its path). This is somewhat better as FileInfo hides the file name/path validation code and separtes it from the GetXmlDataSet code.

Secondly, as you've noticed by now, we are not doing any raw xml manipulation. We are using the technology to do the dirty jobs for us.

The Complete Code:

The code for the main form follows:

1 comment:

Ismael said...

Finally a good Start into XML using C#.
I really appreciate the way you explain your ideas into working code.
Clean Code nice work.

Ismael Jimenez.