How to use LINQ to XML in C#

How to use LINQ to XML in C#

Hello everyone, in this article we are going to talk about LINQ to XML. In here we will make an example and with this example we are going to create an XML file, then we make basic operations with LINQ to XML like add record, select record on clicking, remove record, update record with this example.

Let's get started.

Firstly you should know what will we do. We are going to create an example and we will keep some employee datas in XML file and we are going to manage the related XML file from our C# created program. All database management systems have four basic instructions. These are INSERT, SELECT, DELETE and UPDATE. We are going to make the same operations with our example on an XML file.

First take a look at my application form on below image:

Linq to XML Example Form

First I want to declare my important variables at the top of the program. I will use the required file path and the element names from these variables to prevent any confussion during the development. I also make them const and so reduced the memory consumption.


        public const string xml_path = "employees.xml";
        public const string root_Element = "Employees";
        public const string second_element = "Employee";

        public const string elementName_ID = "ID";
        public const string elementName_Name = "Name";
        public const string elementName_Surname = "Surname";
        public const string elementName_Role = "Role";
        public const string elementName_Salary = "Salary";

After we declared our const variables. first we create the method which creates the XML file if there is no XML file to keep datas. So what will we do to make this:

In this function we will use the XmlTextWriter to create an XML file. First, Here we will create it and we write the created date inside the file as a comment. We must write the root element of the XML firstly If we do not the program will not run and throw an exception which specifies there is no root element. And we finis the writing the XML file. Then we close the XML file writer.

Below code block you will see it:


        //First I will write a function which will create the XML file if there is no XML file
        public void createXMLFile()
        {
            //In this function we will use the XmlTextWriter to create an XML file.
            XmlTextWriter xmlWriter = new XmlTextWriter(xml_path, UTF8Encoding.UTF8);
            xmlWriter.WriteStartDocument();
            //First, Here we will create it and we write the created date inside the file as a comment.
            xmlWriter.WriteComment("XML File Created at first time at : " + DateTime.Now.ToString());
            //We must write the root element of the XML firstly
            //If we do not the program will not run and throw an exception 
            //which specifies there is no root element. 
            xmlWriter.WriteStartElement(root_Element);
            //And we finis the writing the XML file
            xmlWriter.WriteEndDocument();
            xmlWriter.Close();
        }

If we are sure the XML file created now we are ready add add some records.

In here We write a method to add a new element into the XML file under the main element with secon layer element. To make anything with the XML file, first we have to check the file exist

We write a method to add a new element into the XML file under the main element with secon layer element. And then load the xml document. After loading the element we must select the root element which we will work on.One of the most important thing of a record is RECORD ID value. XML has no such thing Auto Identity, so we will count how many record exist in the XML and we will increase the element count for new record. And then we will create new Element under selected Root Element. And then we will create new Element under selected Root Element. This element layer will be second layer and all employee elements will be this element. So we create all employee elements with this tag.

We will set the element id as Attribute of the element. You can add comments above of all new elements with XComment. And add it under thhe main_element After all process do not forget to save the document. After all we will do something To show the user the updates, load the records again.


        public void addNewEmployee()
        {
            //To make anything with the XML file, first we have to check the file exist
            //and if not exist, we must create the XML file with required root element
            if (File.Exists(xml_path) == false)
                createXMLFile();

            //And then load the xml document.
            XDocument document = XDocument.Load(xml_path);
            if (document != null)
            {
                //After loading the element we must select the root element which we will work on.
                XElement main_element = document.Element(root_Element);
                //One of the most important thing of  a record is RECORD ID value.
                //XML has no such thing Auto Identity, so we will count how many record exist in the XML
                //and we will increase the element count for new record.
                int employeeID;
                try { employeeID = document.Descendants(second_element).Max(id => (int)id.Attribute(elementName_ID)); }
                catch { employeeID = 0; }
                employeeID++;
                //And then we will create new Element under selected Root Element.
                //This element layer will be second layer and all employee elements will be this element
                //So we create all employee elements with this tag.
                XElement element = new XElement(new XElement(second_element,
                    new XElement(elementName_Name, txtName.Text),
                    new XElement(elementName_Surname, txtSurname.Text),
                    new XElement(elementName_Role, txtRole.Text),
                    new XElement(elementName_Salary, txtSalary.Text)));
                //We will set the element id as Attribute of the element.
                element.SetAttributeValue(elementName_ID, employeeID);
                //You can add comments above of all new elements with XComment.
                element.AddFirst(new XComment("New Employee ID : " + employeeID));
                //And add it under thhe main_element
                main_element.Add(element);
                //After all process do not forget to save the document.
                document.Save(xml_path);

                MessageBox.Show("Employee added successfully");

                txtID.Text = "";
                txtName.Text = "";
                txtSurname.Text = "";
                txtRole.Text = "";
                txtSalary.Text = "";
                //To show the user the updates, load the records again.
                loadEmployees();
            }
        }

Now we need to load all items into the listview to select them.

First clear the listview to load records and we check the is exist. if the file is exist load the XML document. We load all second layer elements with XElement type in an Enumerable under Root Element. If there is a record Load all records to the listview

Below code block you will see how we did it.


        public void loadEmployees()
        {
            //First clear the listview to load records
            lstEployees.Items.Clear();
            //and we check the is exist
            if (File.Exists(xml_path))
            {
                //if the file is exist load the XML document
                XDocument document = XDocument.Load(xml_path);
                if (document != null)
                {
                    //We load  all second layer elements with XElement type in an Enumerable under Root Element
                    IEnumerable<XElement> employees = from f in document.Element(root_Element).Elements(second_element)
                                                 select f;
                    //If there is a record
                    if (employees.Count() > 0)
                    {
                        //Load all records to the listview
                        foreach (XElement emp in employees) 
                        {
                            ListViewItem item1 = new ListViewItem(emp.Attribute(elementName_ID).Value);
                            item1.SubItems.Add(emp.Element(elementName_Name).Value);
                            item1.SubItems.Add(emp.Element(elementName_Surname).Value);
                            item1.SubItems.Add(emp.Element(elementName_Role).Value);
                            item1.SubItems.Add(emp.Element(elementName_Salary).Value);
                            lstEployees.Items.Add(item1);
                        }
                        lblTotalEmployee.Text = "Total Employee : " + employees.Count();
                    }
                }
            }
        }

Now we have to select the item to make some operations on single records. So we must select items and load its datas into the textboxes to make changings on element.

We will do it on listview click event. Below code block you will see it.


     //Load the record data to the textboxes
     txtID.Text = lstEployees.SelectedItems[0].SubItems[0].Text.ToString();
     txtName.Text = lstEployees.SelectedItems[0].SubItems[1].Text.ToString();
     txtSurname.Text = lstEployees.SelectedItems[0].SubItems[2].Text.ToString();
     txtRole.Text = lstEployees.SelectedItems[0].SubItems[3].Text.ToString();
     txtSalary.Text = lstEployees.SelectedItems[0].SubItems[4].Text.ToString();

We may need to update some employee data. To do this after selection we will update datas.

First load the xml document. Then select the element with the specified ID value to update. Here we created an XElement from the document's root element. And then we select the second layer element with where condition we specified the selected second layer element must have a Attribute value that we specified in txtID and then select appropraite employee record in here.

If selected element is not null, I mean there is a record with specified ID value. Last do not forget to save the XML file. Lastly Loading the entire records will be good.

Below code block you will how did we do it.


        public void updateEmployee()
        {
            //First load the xml document.
            XDocument document = XDocument.Load(xml_path);
            if (document != null)
            {
                //First select the element with the specified ID value to update.
                //Here we created an XElement from the document's root element. And then we select the second layer element
                //with where condition we specified the selected second layer element must have a Attribute value that we specified in txtID
                //and then select appropraite employee record in here.
                XElement element = (from f in document.Element(root_Element).Elements(second_element)
                                      where f.Attribute(elementName_ID).Value == txtID.Text
                                      select f).SingleOrDefault();
                //If selected element is not null, I mean there is a record with specified ID value
                if (element != null)
                {
                    //Start to update elements' value from textboxes
                    element.SetElementValue(elementName_Name, txtName.Text);
                    element.SetElementValue(elementName_Surname, txtSurname.Text);
                    element.SetElementValue(elementName_Role, txtRole.Text);
                    element.SetElementValue(elementName_Salary, txtSalary.Text);
                    //Last do not forget to save the XML file.
                    document.Save(xml_path);

                    MessageBox.Show("Employee updated successfully.");

                    txtID.Text = "";
                    txtName.Text = "";
                    txtSurname.Text = "";
                    txtRole.Text = "";
                    txtSalary.Text = "";
                    //Loading the entire records will be good.
                    loadEmployees();

                }
            }
        }

And we may want to remove some records. To do this first we select the record and then make removing.

To remove a record from the XML file. First we load the element and we select the specified element with the specified attribute value. If there is record with specified ID value Remove the element and save the XML document. When operation is finished, reload the all records.


        //To remove a record from the XML file.
        public void removeEmployee()
        {
            //First we load the element 
            XElement element = XElement.Load(xml_path);
            //and we select the specified element with the specified attribute value.
            var employee = from f in element.Elements(second_element)
                       where f.Attribute(elementName_ID).Value == txtID.Text
                       select f;
            //If there is record with specified ID value
            if (employee != null)
            {
                //Remove the element
                employee.Remove();
                //and save the XML document
                element.Save(xml_path);

                MessageBox.Show("Employee removed successfully.");

                txtID.Text = "";
                txtName.Text = "";
                txtSurname.Text = "";
                txtRole.Text = "";
                txtSalary.Text = "";
                //When operation is finished, reload the all records.
                loadEmployees();
            }
        }

And lastly we may want to make a dynamic search in the XML file.

To make a live search first clear the listview and the check file is exist. Load the document. Here we get the records under root element that contains the text in Searchbox. Here you should make it all texts toLower, Because C# is capital letter sensitive language. And load the records in the listview if there is record more than one.


            //To make a live search first clear the listview
            lstEployees.Items.Clear();
            //and the check file is exist
            if (File.Exists(xml_path))
            {
                //Load the document
                XDocument document = XDocument.Load(xml_path);
                if (document != null)
                {
                    //Here we get the records under root element that contains the text in Searchbox.
                    //Here you should make it all texts toLower, 
                    //Because C# is capital letter sensitive language. 
                    IEnumerable<XElement> employees = from f in document.Element(root_Element).Elements(second_element)
                                                 where f.Element(elementName_Name).Value.ToLower().Contains(txtSearch.Text.ToLower())
                                                 select f;
                    //And load the records in the listview if there is record more than one.
                    if (employees.Count() > 0)
                    {
                        foreach (XElement emp in employees) 
                        {
                            ListViewItem item1 = new ListViewItem(emp.Attribute(elementName_ID).Value);
                            item1.SubItems.Add(emp.Element(elementName_Name).Value);
                            item1.SubItems.Add(emp.Element(elementName_Surname).Value);
                            item1.SubItems.Add(emp.Element(elementName_Role).Value);
                            item1.SubItems.Add(emp.Element(elementName_Salary).Value);
                            lstEployees.Items.Add(item1);
                        }
                    }
                }
            }

Our program is ready.

Below you can see the program while in progress.

Program Window:

Linq to XML Example Program Output

XML File:

Linq to XML Example XML Output
You can reach the example application via https://github.com/thecodeprogram/LinqToXML_Example.

That is all in this article.

Have good XML Managing.

I wish you all have healthy days.

Burak hamdi TUFAN


Tags


Share this Post

Send with Whatsapp

Post a Comment

Success! Your comment sent to post. It will be showed after confirmation.
Error! There was an error sending your comment. Check your inputs!

Comments

  • There is no comment. Be the owner of first comment...