How to use xdocument in c#

How to use xdocument in c#
In this article [Show more]

    How to Use XDocument in C#

    XDocument is a powerful tool in C# that is part of the LINQ to XML API, offering a modern approach to handling XML data. It allows you to load, query, modify, and save XML data in an efficient and straightforward way. This article will explore how to use XDocument effectively, including examples of common operations.

    Creating an XDocument

    You can create an XDocument from scratch, load it from a file, or parse it from a string. Here’s how you can do each:

    From Scratch

     

    XDocument xdoc = new XDocument(
        new XElement("Books",
            new XElement("Book",
                new XElement("Title", "Programming C#"),
                new XElement("Author", "Liberty")
            )
        )
    );
    

    Loading from a File

     

    XDocument xdoc = XDocument.Load("books.xml");
    

    Parsing from a String

     

    string xmlString = @"<Books><Book><Title>Programming C#</Title><Author>Liberty</Author></Book></Books>";
    XDocument xdoc = XDocument.Parse(xmlString);
    

    Querying XML

    Using LINQ with XDocument makes querying XML documents intuitive and flexible. You can easily extract data from deep or complex XML structures.

    Query Example

     

    var titles = from book in xdoc.Descendants("Book")
                 select book.Element("Title").Value;
    
    foreach (var title in titles)
    {
        Console.WriteLine(title);
    }
    

    Modifying XML

    XDocument allows you to modify XML by adding or removing elements and attributes.

    Adding an Element

     

    xdoc.Root.Add(new XElement("Book",
        new XElement("Title", "Learning C#"),
        new XElement("Author", "Smith")
    ));
    

    Removing an Element

     

    var book = xdoc.Descendants("Book").FirstOrDefault(b => b.Element("Title").Value == "Programming C#");
    book?.Remove();
    

    Saving the XML

    After making changes to an XDocument, you can save the document back to a file or elsewhere.

    Saving to a File

     

    xdoc.Save("updatedBooks.xml");
    

    Conclusion

    XDocument is an essential tool for developers working with XML in C#. It combines the flexibility of LINQ with the power of XML manipulation, making it an ideal choice for modern .NET applications that need to process XML data efficiently.


     

    Author Information
    • Author: Ehsan Babaei

    Send Comment



    Comments