Click here to Skip to main content
Click here to Skip to main content

Basics of Handling XML using LINQ

, 14 Apr 2009
Rate this:
Please Sign up or sign in to vote.
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 version="1.0" encoding="utf-8"?>
    <users>
      <user>
        <name>admin</name>
        <password>password</password>
      </user>
      <user1>
        <name>admin</name>
        <password>password</password>
      </user1>
    </users>
    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.
    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:
    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:
    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)

About the Author

KSuthar

India India
No Biography provided

Comments and Discussions

 
GeneralMultiple users Pinmembervirdigs22-May-11 21:03 
GeneralRe: Multiple users PinmemberKSuthar22-May-11 22:53 
GeneralMy vote of 4 Pinmembervirdigs22-May-11 21:00 
Just needs "multiple user" update in this code. Very easy to understand.

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140721.1 | Last Updated 14 Apr 2009
Article Copyright 2009 by KSuthar
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid