Click here to Skip to main content
6,933,832 members and growing! (9,810 online)
Email Password   helpLost your password?
 
Database » Database » General     Intermediate

An XML Database Schema And Data Editor

By Marc Clifton

View and edit your XML database schema and data
C#.NET1.0, Win2K, WinXP, DBA, Dev
Posted:29 Sep 2002
Views:127,490
Bookmarked:109 times
printPrint Friendly   add Share
      Discuss Discuss   Broken Article?Report  
48 votes for this article.
Popularity: 7.37 Rating: 4.38 out of 5
5 votes, 11.1%
1
1 vote, 2.2%
2
1 vote, 2.2%
3
4 votes, 8.9%
4
34 votes, 75.6%
5

Sample Image - xmlSchemaEditor.jpg

Introduction

After publishing my recent article on dynamic menus in C#, several people commented that I should implement the menu structure in XML instead of Access. Well...fine, I thought, and began playing around with XML schemas in the VS.NET IDE. I was quickly disappointed with the ability to create schemas and edit their contents. The IDE was not behaving as the documentations said it should, and the behavior appeared inconsistent and buggy. Several of you commented that you were not getting this behavior, but I was. I also wanted an XML schema/data editor that was independent of the IDE (regardless of the 20MB dotnetfx.exe file that needs to be installed!).

After browsing CP and google, I didn�t see anything that fell into the category of a basic schema and data editor, so the following is the result. Even if I�ve duplicated effort, I�ve learned some things on the way, and having no prior XML experience, this is probably where the greatest value lies.

There really isn't anything that's rocket science about this, but I'll show some code anyways.

Loading An XML File

private void mnuOpen_Click(object sender, System.EventArgs e)
{
    DialogResult res=openFileDialog.ShowDialog(this);
    if (res==DialogResult.OK)
    {
        string fn=openFileDialog.FileName;
        DataSet ds=new DataSet();
        ds.ReadXml(fn);
        lbTables.Items.Clear();
        foreach (DataTable dt in ds.Tables)
        {
            lbTables.Items.Add(dt.TableName);
        }
        dataSet=ds;
        lbTables.SelectedIndex=0;
        fnSchema=fn;
        this.Text="XML Database Editor - "+fnSchema;
    }
}

This code, after getting a valid XML filename (to the limits that I test it!), loads the file into a DataSet, which is a built in function of the DataSet. The table ListBox lbTables is then populated with the table name, by iterating through the data set's tables. The first table is selected as default, and the application caption is updated.

Saving A DataSet As An XML File

dataSet.WriteXml(fn, XmlWriteMode.WriteSchema);

This statement writes all the data for all the tables, and with the XmlWriteMode.WriteSchema option, also writes the schema for the DataSet. Thus, the XML file has the complete description of the database and all of its data.

Adding A Table

Tables are added to the DataSet as described below:

private void btnAddTable_Click(object sender, System.EventArgs e)
{
    string tblName=edTableName.Text;
    if (!ValidateTableName(tblName))
    {
        return;
    }
    
    DataTable dt=new DataTable(tblName);
    currentTable=dt;
    lbTables.Items.Add(tblName);
    dataSet.Tables.Add(dt);
    lbTables.SelectedItem=lbTables.Items[lbTables.FindStringExact(tblName)];
}

This code adds a table to the ListBox and to the DataSet, then selects the newly added table in the ListBox.

Adding A Column

Columns are added to the currently selected table:

private void btnAddColumn_Click(object sender, System.EventArgs e)
{
    string colName=edColumnName.Text;
    string colType=cbColumnType.Text;
    if ( (!ValidateColumnNameAndType(colName, colType)) || 
                                (!ValidateSelectedTable()) )
    {
        return;
    }
    ListViewItem lvi=lvColumns.Items.Add(colName);
    lvi.SubItems.Add(colType);
    currentTable.Columns.Add(colName, Type.GetType("System."+colType));
}

In the above code, the column is added to the column ListView and to the selected table. Observe the code:

currentTable.Columns.Add(colName, Type.GetType("System."+colType));

When adding a column, the column name and the type is required. The type is determined by using a great VS.NET function GetType, which converts a textual representation of the string to its actual type. In the code, the string "System." is prefixed onto the column type string so that the conversion routine can find the correct type. The "System." is removed when displaying column types in the ListView with the string Split function, as described below.

Displaying A Table's Columns

void ShowColumns()
{
    lvColumns.Items.Clear();
    if (currentTable != null)
    {
        foreach (DataColumn dc in currentTable.Columns)
        {
            ListViewItem lvi=lvColumns.Items.Add(dc.ColumnName);
            string s=dc.DataType.ToString();
            s=s.Split(new Char[] {'.'})[1];
            lvi.SubItems.Add(s);
        }
    }
}

This code iterates through the columns of the current table, extracting the column name and the column data type, then adding this information to the ListView.

The Data Grid

Probably the most interesting process is setting up the DataGrid. The DataGrid displays data for the selected table:

private void lbTables_SelectedIndexChanged(object sender, 
                                        System.EventArgs e)
{
    string tblName=lbTables.Text;
    currentTable=dataSet.Tables[tblName];
    ShowColumns();
    dgData.SetDataBinding(dataSet, tblName);
    dgData.CaptionText="Table: "+tblName;
}

The SetDataBinding function is used to establish the connection between the DataGrid and the specific table in the DataSet. Quite nicely, whenever you change the name of the table or column, or add/remove columns, the DataSet automatically updates. There is no code required to update the DataGrid. Amazing!

Possible VS.NET bug?

One thing I noticed was that, when deleting a table from the DataSet, the table still "lingers" in the DataGrid. If you add a table with the same name, back into the system, you will notice that it already has columns defined in the DataGrid. Very strange behavior!

Conclusion

This was a very simple utility to put together and demonstrate some nice things about VS.NET, and some quirks. For example, you can't change the data type of a column after it has data. The program could be extended to do this manually, I suppose. But for now, I don't allow it either (which is too bad, because I occasionally need to change the data type with existing data).

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Marc Clifton


Member
Marc is the creator of two open source projets, MyXaml, a declarative (XML) instantiation engine and the Advanced Unit Testing framework, and Interacx, a commercial n-tier RAD application suite.  Visit his website, www.marcclifton.com, where you will find many of his articles.

Marc lives in Philmont, NY with his son Ian.
Occupation: Architect
Company: Interacx
Location: United States United States

Other popular Database articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 20 of 20 (Total in Forum: 20) (Refresh)FirstPrevNext
Generalfrom DataTable to Query Designer PinmemberAtzsea Hiducca10:49 13 Nov '09  
GeneralThanks Pinmemberwas3330:17 5 Nov '08  
QuestionNeed help to read My Advanced XML PinmemberPrithwish Biswas1:41 11 Apr '08  
GeneralFit the Bill PinmemberOnskee112:21 16 Dec '07  
GeneralYet another great article! PinmemberPreky23:11 7 Oct '07  
GeneralHierarchies PinmemberHypnotron7:37 13 Sep '07  
Seems to me the strength of XML when it comes to being used to store data is the ease at which it handles hierarchies and particularly hierarchies with unlimited depth. Using it in the way that you do, you pretty much remove this advantage. I had been looking at storing some hierarchical data in a relational database but have since decided that an XML database is better suited. My main problem is I expect to have _very_ large XML databases with arbitrary hierarchy depths and I also dont want to have the entire document loaded in memory at once. I may end up doing what originally made me look into relational databases in the first place and that is using alot of smaller seperate XML files and handling the file management myself. I know that I could use a relational DB to hold XML text but at that point I dont see the point in having the overhead of an embedded db just to store XML.

For now I'm going to try and modify the interface to your program to work with nested hierarchies.


GeneralVB version Pinmembershalan993:31 27 Jun '07  
GeneralLife Saver PinmemberPriyank Bolia5:24 17 Jun '07  
GeneralHow do i change the column width PinmemberSudhanshu Gupta2:43 10 Jun '06  
GeneralRe: How do i change the column width PinmemberJeremy L-T20:15 15 Jun '06  
GeneralCreating database from xml Pinmemberw3Nima3:12 13 May '06  
GeneralXML Dokument Pinmembersurfman1913:39 19 Aug '05  
GeneralRe: XML Dokument Pinmembertwostepted20:03 30 Oct '05  
GeneralFrom XML to Relation Database Pinmemberdoxuanhuyen3:37 12 Mar '03  
GeneralRe: From XML to Relation Database PinmemberMarc Clifton9:01 12 Mar '03  
GeneralProblem with PART Table Pinmemberfmarchi11:39 20 Nov '02  
GeneralMalformed XML PinmemberJon Taylor23:08 2 Oct '02  
GeneralNice DataSet tutorial Pinmemberrhoward14:05 1 Oct '02  
GeneralRe: Nice DataSet tutorial PinmemberMarc Clifton14:10 1 Oct '02  
GeneralRe: Nice DataSet tutorial PinmemberAlexpro23:55 2 Oct '02  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+PgUp/PgDown to switch pages.

PermaLink | Privacy | Terms of Use
Last Updated: 29 Sep 2002
Editor: Smitha Vijayan
Copyright 2002 by Marc Clifton
Everything else Copyright © CodeProject, 1999-2010
Web18 | Advertise on the Code Project