<Employees>" /> <Employees>" />
read XML file in c# using LINQ

Updated : Oct 22, 2019 in Articles

How to read XML file in c# using LINQ

In this article, we will learn how to read XML file in c# using LINQ

Go to visual studio create windows application and design the GUI look given below

read XML file in c# using LINQ
LINQ to XML examples

Add an XML file in your application name like Employees.xml inside XML file you add some data about employee details you can see given below XML file

<?xml version="1.0" encoding="utf-8" ?>
<Employees>
  <Employee EmpId="1">
    <Name>E1</Name>
    <Salary>1000</Salary>
  </Employee>
  <Employee EmpId="2">
    <Name>E2</Name>
    <Salary>2000</Salary>
  </Employee>
  <Employee EmpId="3">
    <Name>E3</Name>
    <Salary>1200</Salary>
  </Employee>
  <Employee EmpId="4">
    <Name>E4</Name>
    <Salary>1100</Salary>
  </Employee>
  <Employee EmpId="5">
    <Name>E5</Name>
    <Salary>1300</Salary>
  </Employee>
</Employees>

you will read the Employees.xml file in page load by using XDocument class

XDocument doc;
 private void Form1_Load(object sender, EventArgs e1)
 {
   doc = XDocument.Load("Employees.xml");
 }

you will read the XML nodes with the help of the Descendants from Employees.xml file as a list

follow the given below code for a read XML file in c# using LINQ
 private void btnViewEmployees_Click(object sender, EventArgs e1)
        {
            var emps = from e in doc.Descendants("Employee")
                       //where int.Parse(e.Attribute("EmpId").Value) > 3
                       select new { Id = e.Attribute("EmpId").Value, Name = e.Element("Name").Value, Salary = e.Element("Salary").Value };
            string strEmps = "";
            foreach (var emp in emps)
                strEmps += emp.Id + " " + emp.Name + " " + emp.Salary + "\n";
            MessageBox.Show(strEmps);
        }
linq to xml converting
LINQ to XML Example

we will perform curd operation on an existing object like insert and update delete

Create New XML

We will create a file format XML with the help of the XElement class this class can contain XAttribute(), XElement() methods, by using these methods we will create an XML file at run time

The formed XML file should be converted into the XML document for this we will use XDocument class this document class can have two methods XDeclaration(), XComment()

We will pass the parameters to Xdeclaration() method like version, encoding, standalone. XComment () method will represent the XML file data

 private void btnCreateNewXml_Click(object sender, EventArgs e)
        {
            XElement emps =
            new XElement("Employees",
            new XElement("Employee",
                    new XAttribute("EmpId", 1),
                    new XElement("Name", "Sam"),
                    new XElement("Salary", 1000)),
            new XElement("Employee",
                    new XAttribute("EmpId", 2),
                    new XElement("Name", "Sarita"),
                    new XElement("Salary", 2000)),
            new XElement("Employee",
                    new XAttribute("EmpId", 3),
                    new XElement("Name", "Kishore"),
                    new XElement("Salary", 3000)),
            new XElement("Employee",
                    new XAttribute("EmpId", 4),
                    new XElement("Name", "Harish"),
                    new XElement("Salary", 4000))
            );
            XDocument doc = new XDocument(
                    new XDeclaration("1.0", "utf8", "yes"),
                    new XComment("This is dynamically created list of Employees"),
                    emps);
            doc.Save("Employees.xml");

        }
read xml file linq
read XML file in LINQ

Update XML

we will update the existing XML file at run time for this will replace a node value with a new updating value

 private void btnUpdateEmployee_Click(object sender, EventArgs e)
        {
            XElement emps = doc.Element("Employees");
            XElement emp = (XElement)emps.Nodes().ElementAt(2);
            emp.Element("Name").ReplaceNodes("New Value");
            doc.Save("Employees.xml");
        }

Add XML

Add XML file means we will save some new data to existing XML data

private void btnAddEmployee_Click(object sender, EventArgs e)
        {
            XElement emps = doc.Element("Employees");
            emps.Add(new XElement("Employee",
                            new XAttribute("EmpId", 5),
                            new XElement("Name", "Ramesh"),
                            new XElement("Salary", 8000)));
            doc.Save("Employees.xml");
        }

Delete XML

if we want to delete an XML data in object first we will find the node position see the given below code

 private void btnDeleteEmployee_Click(object sender, EventArgs e)
        {
            XElement emps = doc.Descendants("Employees").Single();
            emps.Nodes().ElementAt(2).Remove();
            doc.Save("Employees.xml");
        }
delete xml from object
delete XML from object

The above example Employee.xml file is static file instead of that create an Employee table in SQL server and return the table format like XML, try to bind the value to the application

[Table(Name = "Employee")]
class Employee
{
    [Column(Name = "EmpId", IsPrimaryKey = true)]
    public int Id;
    [Column(Name = "EmpName")]
    public string Name;
    [Column(Name = "EmpSalary")]
    public decimal Salary;
}
class Program
{
    static void Main(string[] args)
    {
        string cs = "Data Source=yourname\\SQLEXPRESS;Initial Catalog=LinqDemoDb;Integrated Security=True;";
        DataContext dc = new DataContext(cs);
        Table<Employee> tabEmps = dc.GetTable<Employee>();
        foreach (var emp in tabEmps)
        {
            Console.WriteLine(emp.Id + " " + emp.Name + " " + emp.Salary + "\n");          
        }
        dc.Dispose();
        Console.Read();
    }
}

thanks

Like
Like Love Haha Wow Sad Angry
28

Subscribe
Notify of
guest
5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Branden Montayes
March 26, 2020 9:48 pm

Bookmarked!, I really like your web site!

Megan Partington
April 8, 2020 1:41 pm

First time visiting your website, I really like your blog!

Google
April 13, 2020 3:43 pm

Usually posts some pretty interesting stuff like this. If youre new to this site.

Marry Hubka
April 19, 2020 10:43 pm

First time visiting your website, I really like your web site!

Virgilio Sifontes
Virgilio Sifontes
April 25, 2020 7:44 pm

Bookmarked!, I love your blog!

5
0
Would love your thoughts, please comment.x
()
x