Click here to Skip to main content
15,860,859 members
Articles / Web Development / ASP.NET

Basics of Handling XML using LINQ

Rate me:
Please Sign up or sign in to vote.
4.17/5 (9 votes)
14 Apr 2009CPOL1 min read 45K   1K   27   3
Create, read and write XML file using LINQ

Introduction

I am a beginner as far as C# and especially XML are concerned. To learn about XML handling, I read many documents on the internet and on CodeProject. But they are too complex for beginners to understand at first. Here, I summarize whatever I learned about XML handling.

Background

I will show you how to create an XML file, read the value in the program and update the values back to XML file. I don't know much about LINQ, but it is used here to read from the XML file. To me, it seems to be the easiest way.

Using the Code 

I wrote these four methods: 

  1. CreateXMLFile() - If file does not exist, create it using XElement and save it. It creates the following XML file:
    XML
    <?xml version="1.0" encoding="utf-8"?>
    <users>
      <user>
        <name>admin</name>
        <password>password</password>
      </user>
      <user1>
        <name>admin</name>
        <password>password</password>
      </user1>
    </users>
    C#
    public void CreateXMLFile()
    {
        string fileName = "XMLFile.xml";
        string valuename = "admin", valuepassword = "password";
         if (!File.Exists(fileName))
        {
            XElement users =
                new XElement("users",
                    new XElement("user",
                        new XElement("name", valuename),
                        new XElement("password", valuepassword))
                   ,new XElement("user1",
                        new XElement("name", valuename),
                        new XElement("password", valuepassword))
                        );
            users.Save(fileName);
            MessageBox.Show("XML File Created");
        }
        else
        {
            MessageBox.Show("XML File Already Exists");
        }
    } 
  2. LoadXMLFile() -  To read values from XML file, use XElement and LINQ query. You can read more about LINQ here.
    C#
    public void LoadXMLFile()
    {
        string fileName = "XMLFile.xml";
        if (!File.Exists(fileName))
        {
            MessageBox.Show("Create XML File before Loading");
        }
        else
        {
            XElement dataElements = XElement.Load(fileName);
            //Following is a LINQ Query
            textBox1.Text = new XElement("users",
                (from c in dataElements.Elements("user")
                 select new XElement("user", c.Element("name"))).Take(1)).Value;
            textBox2.Text = new XElement("users",
                (from c in dataElements.Elements("user")
                 select new XElement("user", c.Element("password"))).Take(1)).Value;
        }
    } 
  3. SaveXMLFile() - To update a specific node, you need to trace it using Element method of XElement. To replace the value, use ReplaceNodes method:
    C#
    public void SaveXMLFile()
    {
        string fileName = "XMLFile.xml";
        if (!File.Exists(fileName))
        {
            CreateXMLFile();
        }
        //Load the XML File
        XElement dataElements = XElement.Load(fileName);
         dataElements.Element("user").Element("name").ReplaceNodes(textBox1.Text);
        dataElements.Element("user").Element("password").ReplaceNodes(textBox2.Text);
         // Save the file
        dataElements.Save(fileName);
    }
  4. DeleteXMLFile() - This uses the basic System.IO. If the file exists, delete it using File.Delete:
    C#
    public void DeleteXMLFile()
    {
        string fileName = "XMLFile.xml";
        if (File.Exists(fileName))
        {
            File.Delete(fileName);
            MessageBox.Show("XML File Deleted");
        }
        else
        {
            MessageBox.Show("Create XML File before Deleting");
        }
    } 

History

  • V1.0 April 12th 2009: Initial version
    This is the first version of the article, and it is my first article on CodeProject, so suggestions on improving the style of writing and anything else are welcome.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMultiple users Pin
gs_virdi22-May-11 21:03
gs_virdi22-May-11 21:03 
GeneralRe: Multiple users Pin
Karmendra Suthar22-May-11 22:53
Karmendra Suthar22-May-11 22:53 
GeneralMy vote of 4 Pin
gs_virdi22-May-11 21:00
gs_virdi22-May-11 21:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

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