Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » WPF » CRUD Operation on XML DB in WPF Application

CRUD Operation on XML DB in WPF Application

In this article we will see how to perform CRUD operation on an XML database in a WPF application.

Author Rank :
Page Views : 8980
Downloads : 542
Rating :
 Rate it
Level : Advanced
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
CRUDXmlDbWPF.zip | MovieDB.zip
 
 
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 



Introduction

In this article we will see how to perform CRUD operation on an XML database in WPF.

CRUD1.gif

Creating WPF Application

Fire up Visual Studio and create a WPF Application, name it as CRUDXmlDbWPF.

We need to design for CRUD operation. I preferred Blend 3 and used Tab Control.

CRUD2.gif


CRUD3.gif

CRUD4.gif

XML Schema in C# Class

Create a class of your xml schema.

class Movies
    {
        public string Name { get; set; }
        public string Genre { get; set; }
        public string Cast { get; set; }
        public string Year { get; set; }
    }

Global Variables

The following are the Global variables I have used.

ObservableCollection<Movies> selectedList = new ObservableCollection<Movies>();
List<Movies> movieList;
List<string> yearList;
Movies moviesDel;

        public Window1()
        {
            InitializeComponent();
            btnUpdate.IsEnabled = false;
            btnDelete.IsEnabled = false;
            yearList = new List<string> { "2010", "2009", "2008", "2007", "2006", "2005", "2004", "2003" };
            cmbYear.ItemsSource = yearList;
            cmbYearUpdate.ItemsSource = yearList;
            LoadData();
        }

Read Operation

We have an xml file named MovieDB.xml in the root directory. I have created a method to load data from the file.

#region Load Data
        void LoadData()
        {
            XDocument doc = XDocument.Load(@"E:\MovieDB.xml");
            movieList = (from movie in doc.Descendants("Movie")
                       orderby movie.Element("Name").Value
                       select new Movies
                       {
                           Name = movie.Element("Name").Value,
                           Genre = movie.Element("Genre").Value,
                           Year = movie.Element("Year").Value,
                           Cast = movie.Element("Cast").Value,
                       }).ToList();

            lbMovies.ItemsSource = movieList;
            ViewDataGrid.ItemsSource = movieList;

        }        #endregion

Call the method whenever and wherever it is required to Load data.

Create and Update Operation

Create and Update operations are same except that we update an existing data in Update Operation.

So I have created a method called WriteToXml where I am writing to XML file depending on the Create or Update Operation.

#region WriteToXmlFile
        void WriteToXmlFile(Movies movies, bool isUpdate)
        {
            #region Add New
            if (!isUpdate)
            {
                FileStream fs = new FileStream(@"E:\MovieDB.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(fs);
                fs.Close();

                XmlElement newMovie = xmlDoc.CreateElement("Movie");
                XmlElement name = xmlDoc.CreateElement("Name");
                name.InnerText = movies.Name;
                newMovie.AppendChild(name);

                XmlElement genre = xmlDoc.CreateElement("Genre");
                genre.InnerText = movies.Genre;
                newMovie.AppendChild(genre);

                XmlElement year = xmlDoc.CreateElement("Year");
                year.InnerText = movies.Year;
                newMovie.AppendChild(year);

                XmlElement cast = xmlDoc.CreateElement("Cast");
                cast.InnerText = movies.Cast;
                newMovie.AppendChild(cast);

                xmlDoc.DocumentElement.InsertAfter(newMovie,
                xmlDoc.DocumentElement.LastChild);

                FileStream fsxml = new FileStream(@"E:\MovieDB.xml", FileMode.Truncate,
                                      FileAccess.Write,
                                      FileShare.ReadWrite);

                xmlDoc.Save(fsxml);
                fsxml.Close();
            }
            #endregion

            #region Update
            else
            {
                XDocument doc = XDocument.Load(@"E:\MovieDB.xml");

                foreach (var item in doc.Descendants("Movie"))
                {
                    if (item.Element("Name").Value == moviesDel.Name)
                    {
                        item.Element("Name").SetValue(movies.Name);
                        item.Element("Genre").SetValue(movies.Genre);
                        item.Element("Year").SetValue(movies.Year);
                        item.Element("Cast").SetValue(movies.Cast);
                        doc.Save(@"E:\MovieDB.xml");
                        break;
                    }
                }
            }
            #endregion

        }         #endregion

On Button Click events of Either Create or Update Operation you can call the above method.

#region Add Operation
        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            string name = txtName.Text.Trim();
            string year;
            if (cmbYear.SelectedIndex != -1)
            {
                year = cmbYear.SelectedValue.ToString();
            }
            else
            {
                year = "2009";
            }
            string genre = txtGenre.Text.Trim();
            string cast = txtCast.Text.Trim();
 
            bool isUpdate = false;

            if (name.Equals(string.Empty))
                name = "Un Named Movie";
            if (year.Equals(string.Empty))
                year = "2009";
            if (genre.Equals(string.Empty))
                genre = "No Genre";
            if (cast.Equals(string.Empty))
                cast = "No Cast";

            Movies newMovie = new Movies
            {
                Name = name,
                Year = year,
                Genre = genre,
                Cast = cast,
            };

            WriteToXmlFile(newMovie, isUpdate);
            txtName.Text = string.Empty;
            txtGenre.Text = string.Empty;
            txtCast.Text = string.Empty;
            cmbYear.SelectedIndex = -1;
            LoadData();
        }
        #endregion

        #region Update Operation
        private void btnUpdate_Click(object sender, RoutedEventArgs e)
        {
            if (lbMovies.SelectedIndex != -1)
            {
                string name = txtNameUpdate.Text;
                string year = cmbYearUpdate.SelectedValue.ToString();
                string genre = txtGenreUpdate.Text;
                string cast = txtCastUpdate.Text;

                bool isUpdate = true;

                if (name.Equals(string.Empty))
                    name = "Un Named Movie";
                if (year.Equals(string.Empty))
                    year = "2009";
                if (genre.Equals(string.Empty))
                    genre = "No Genre";
                if (cast.Equals(string.Empty))
                    cast = "No Cast";

                Movies updateMovie = new Movies
                {
                    Name = name,
                    Year = year,
                    Genre = genre,
                    Cast = cast,
                };

                WriteToXmlFile(updateMovie, isUpdate);
                lbMovies.SelectedIndex = -1;
                btnUpdate.IsEnabled = false;
                btnDelete.IsEnabled = false;
                LoadData();
            }
        }
        #endregion

On selection changed of the ListBox perform as below to bind data to the respective fields.

#region ListBox Selection Changed
        private void lbMovies_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            selectedList.Clear();
            if (this.lbMovies.SelectedItem is Movies)
            {
                selectedList.Add(((Movies)this.lbMovies.SelectedItem));
                moviesDel = (Movies)this.lbMovies.SelectedItem;
            }
            foreach (var item in selectedList)
            {
                txtNameUpdate.Text = item.Name;
                cmbYearUpdate.SelectedValue = item.Year;
                txtGenreUpdate.Text = item.Genre;
                txtCastUpdate.Text = item.Cast;
            }
            btnUpdate.IsEnabled = true;
            btnDelete.IsEnabled = true;

        }         #endregion

Delete Operation

On Delete button click event you can add the following code to perform the Delete Operation.

#region Delete Operation
        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            if (moviesDel != null)
            {
                if (System.Windows.MessageBox.Show("Do you Really Want To Delete This Movie ?", "Delete Confirmation", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    XDocument doc = XDocument.Load(@"E:\MovieDB.xml");

                    foreach (var item in doc.Descendants("Movie"))
                    {
                        if (item.Element("Name").Value == moviesDel.Name)
                        {
                            ((XElement)item.Element("Name")).Parent.Remove();
                            doc.Save(@"E:\MovieDB.xml");
                            break;
                        }
                    }
                    LoadData();
                    moviesDel = null;
                    lbMovies.SelectedIndex = -1;
                    btnDelete.IsEnabled = false;
                }
                else
                {
                    moviesDel = null;
                    lbMovies.SelectedIndex = -1;
                    btnDelete.IsEnabled = false;
                }
            }
        }
        #endregion

XAML Binding

The following code refers to XAML data binding and control's properties.

<TabControl Background="{x:Null}">
<
TabItem Header="View All">
<
Grid>
<
Custom:DataGrid x:Name="ViewDataGrid" IsReadOnly="True" GridLinesVisibility="Horizontal"
                                     AutoGenerateColumns="False" d:LayoutOverrides="Width, Height" Background="{x:Null}">
                        <Custom:DataGrid.Columns>
                            <Custom:DataGridTextColumn Header="Movie Name" Binding="{Binding Path=Name}"/>
                            <Custom:DataGridTextColumn Header="Year" Binding="{Binding Path=Year}"/>
                            <Custom:DataGridTextColumn Header="Genre" Binding="{Binding Path=Genre}"/>
                            <Custom:DataGridTextColumn Header="Cast" Binding="{Binding Path=Cast}"/>
                        </Custom:DataGrid.Columns>
</
Custom:DataGrid>
</
Grid>
</
TabItem>
<
TabItem Header="Add New">
<
Grid>
<
Grid.ColumnDefinitions>
<
ColumnDefinition Width="0.217*"/>
<
ColumnDefinition Width="0.783*"/>
</
Grid.ColumnDefinitions>
<
Grid.RowDefinitions>
<
RowDefinition Height="0.083*"/>
<
RowDefinition Height="0.086*"/>
<
RowDefinition Height="0.147*"/>
<
RowDefinition Height="0.146*"/>
<
RowDefinition Height="0.09*"/>
<
RowDefinition Height="0.095*"/>
<
RowDefinition Height="0.353*"/>
</
Grid.RowDefinitions>
<
TextBlock HorizontalAlignment="Right" VerticalAlignment="Center" Text="Name :" TextWrapping="Wrap" Margin="0,0,5,0" Grid.Row="1"/>
<
TextBlock HorizontalAlignment="Right" Margin="0,0,5,0" VerticalAlignment="Center" Text="Genre :" TextWrapping="Wrap" Grid.Row="2"/>
<
TextBlock HorizontalAlignment="Right" Margin="0,0,5,0" VerticalAlignment="Center" Grid.Row="3" Text="Cast :" TextWrapping="Wrap"/>
<
TextBlock HorizontalAlignment="Right" Margin="0,0,5,0" VerticalAlignment="Center" Text="Year :" TextWrapping="Wrap" Grid.Row="4"/>
<
TextBox x:Name="txtName" Margin="0,0,5,0" Grid.Row="1" Grid.Column="1" VerticalAlignment="Center" Height="23"/>
<
TextBox x:Name="txtGenre" Margin="0,1,5,1" Grid.Column="1" Grid.Row="2" TextWrapping="Wrap" VerticalScrollBarVisibility="Visible"/>
<
TextBox x:Name="txtCast" Margin="0,1,5,1" Grid.Column="1" Grid.Row="3" TextWrapping="Wrap" VerticalScrollBarVisibility="Visible"/>
<
ComboBox x:Name="cmbYear" Margin="0" HorizontalAlignment="Left" Width="75" Grid.Column="1" Grid.Row="4" Height="20"
VerticalAlignment="Center"/>
<
Button x:Name="btnAdd" Click="btnAdd_Click"
                            HorizontalAlignment="Left" Margin="0" VerticalAlignment="Center" Width="100" Height="25" Content="Add New" Grid.Column="1"
Grid.Row="5"/>
</Grid>
</
TabItem>
<
TabItem Header="Update">
<
Grid>
<
Grid.ColumnDefinitions>
<
ColumnDefinition Width="0.283*"/>
<
ColumnDefinition Width="0.078*"/>
<
ColumnDefinition Width="0.639*"/>
</
Grid.ColumnDefinitions>
<
Grid.RowDefinitions>
<
RowDefinition Height="0.083*"/>
<
RowDefinition Height="0.086*"/>
<
RowDefinition Height="0.147*"/>
<
RowDefinition Height="0.146*"/>
<
RowDefinition Height="0.09*"/>
<
RowDefinition Height="0.095*"/>
<
RowDefinition Height="0.353*"/>
</
Grid.RowDefinitions>
<
TextBlock Margin="5.711,0,5,0" VerticalAlignment="Center" Grid.Row="1" Text="Name :" TextWrapping="Wrap" Grid.Column="1" d:LayoutOverrides="Width"/>
<
TextBlock Margin="4.834,0,5,0" VerticalAlignment="Center" Text="Genre :" TextWrapping="Wrap" Grid.Row="2" Grid.Column="1" d:LayoutOverrides="Width"/>
<
TextBlock Margin="12.884,0,5,0" VerticalAlignment="Center" Grid.Row="3" Text="Cast :" TextWrapping="Wrap" Grid.Column="1" d:LayoutOverrides="Width"/>
<
TextBlock Margin="11.991,0,5,0" VerticalAlignment="Center" Text="Year :" TextWrapping="Wrap" Grid.Row="4" Grid.Column="1" d:LayoutOverrides="Width"/>
<
TextBox x:Name="txtNameUpdate" Margin="0,0,5,0" VerticalAlignment="Center" Height="23" Grid.Column="2" Grid.Row="1"/>
<
TextBox x:Name="txtGenreUpdate" Margin="0,1,5,1" Grid.Column="2" Grid.Row="2" TextWrapping="Wrap" VerticalScrollBarVisibility="Visible"/>
<
TextBox x:Name="txtCastUpdate" Margin="0,1,5,1" Grid.Column="2" Grid.Row="3" TextWrapping="Wrap" VerticalScrollBarVisibility="Visible"/>
<
ComboBox x:Name="cmbYearUpdate" HorizontalAlignment="Left" Margin="0" VerticalAlignment="Center" Width="75" Height="20" Grid.Column="2"
Grid.Row="4"/>
<
Button x:Name="btnUpdate" Click="btnUpdate_Click"
                            HorizontalAlignment="Left" Margin="0" VerticalAlignment="Center" Width="100" Height="25" Content="Update" Grid.Column="2"
Grid.Row="5"/>
<Button x:Name="btnDelete" Click="btnDelete_Click"
                            Margin="108,0,188.819,0" VerticalAlignment="Center" Height="25" Content="Delete" Grid.Column="2" Grid.Row="5"
Width="100"/>
                    <ListBox x:Name="lbMovies" SelectionChanged="lbMovies_SelectionChanged"
                             Margin="0,8" Grid.RowSpan="7">
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding Name}"/>
                            </DataTemplate>
                        </ListBox.ItemTemplate>
                    </ListBox>
</
Grid>

</TabItem></TabControl>

That's it. Run your application and you would achieve the CRUD operation for XML data.

CRUD5.gif

CRUD6.gif

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Diptimaya Patra

Diptimaya is working as a Sr. Software Engineer in Microsoft Technologies (C#). He is a Microsoft MVP in Client App Dev, he has a good hands on in Silverlight 2/3/4, WPF 3/4, Expression Blend 3/4.


Follow him in Twitter: http://www.twitter.com/dpatra

Blog: http://dpatra.blogspot.com , http://diptimayapatra.wordpress.com

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Missing MovieDB.xml file. by Wilson On January 13, 2010
Hi Diptimaya,

Could you please post your MovieDB.xml file?

Thanks.
Reply | Email | Modify 
Re: Missing MovieDB.xml file. by Diptimaya On January 28, 2010

Hi,

I have uploaded the xml file. In addition you can check the below link for the complete Movie Database Application.

http://dpatratools.wordpress.com/2010/01/01/movie-database/

Thanks
Diptimaya Patra

Reply | Email | Modify 
hey can you upload xml file?? by Raj On January 14, 2010
hey can you upload xml file?? that wud be more help.
Reply | Email | Modify 
Re: hey can you upload xml file?? by Diptimaya On January 28, 2010

Hi,

I have uploaded the xml file. In addition you can check the below link for the complete Movie Database Application.

http://dpatratools.wordpress.com/2010/01/01/movie-database/

Thanks
Diptimaya Patra

Reply | Email | Modify 
Re: Re: hey can you upload xml file?? by Raj On January 29, 2010
Thanks Diptimaya
Reply | Email | Modify 
Thanks by A On June 17, 2010
Thanks a lot dude :)
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.