A Comprehensive Resource for Microsoft Technologies

Welcome, your go-to destination for everything related to .NET and Microsoft technologies. With over 10 years of experience in the IT industry, I am excited to share my knowledge and insights on this platform. This blog is dedicated to providing valuable information, tips, and tutorials that are not only relevant to the rapidly evolving IT industry but also essential for individuals working on real-time projects and preparing for interviews

C# Tutorial 10.3 :LINQ to XML


LINQ to XML is a powerful feature in C# that allows you to query and manipulate XML documents using LINQ (Language Integrated Query). Let's break down the tutorial into several steps.

Step 1: Introduction to LINQ to XML

using System;
using System.Linq;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        // Create a sample XML document
        XElement xmlTree = new XElement("Root",
            new XElement("Element1", "Value1"),
            new XElement("Element2", "Value2"),
            new XElement("Element3", "Value3")
        );

        // Display the XML document
        Console.WriteLine("Original XML:");
        Console.WriteLine(xmlTree);

        // LINQ to XML queries go here

        Console.ReadLine(); // Keep console window open in debug mode
    }
}

Step 2: Basic LINQ to XML Queries

// Query to get all elements with the name "Element2"
var element2 = xmlTree.Elements("Element2");
Console.WriteLine("\nQuery - Elements with name 'Element2':");
foreach (var element in element2)
{
    Console.WriteLine(element);
}

// Query to get the value of Element1
var valueOfElement1 = xmlTree.Element("Element1")?.Value;
Console.WriteLine("\nQuery - Value of Element1:");
Console.WriteLine(valueOfElement1);

Step 3: Creating and Modifying XML with LINQ

// Add a new element to the XML document
xmlTree.Add(new XElement("Element4", "Value4"));

// Modify the value of Element2
var elementToModify = xmlTree.Element("Element2");
if (elementToModify != null)
{
    elementToModify.Value = "NewValue";
}

Console.WriteLine("\nModified XML:");
Console.WriteLine(xmlTree);

Step 4: Filtering with LINQ to XML

// Query to get elements with values containing "Value"
var elementsWithValue = xmlTree.Elements().Where(e => e.Value.Contains("Value"));
Console.WriteLine("\nQuery - Elements with values containing 'Value':");
foreach (var element in elementsWithValue)
{
    Console.WriteLine(element);
}

Step 5: Loading XML from a File

// Load XML from a file
XDocument loadedXml = XDocument.Load("path/to/your/file.xml");
Console.WriteLine("\nLoaded XML from file:");
Console.WriteLine(loadedXml);

Step 6: Saving XML to a File

// Save XML to a file
xmlTree.Save("path/to/your/outputfile.xml");
Console.WriteLine("\nXML saved to file.");

This tutorial covers the basics of LINQ to XML in C#. Feel free to expand upon this foundation and explore more advanced features as needed for your specific use case.