xelement c# example

xelement c# example
In this article [Show more]

    XElement in C#: A Practical Example

    The XElement class is a fundamental part of the LINQ to XML API in C#, which allows developers to work with XML data effortlessly. This article provides a practical example of using XElement to create, manipulate, and query XML data in C#.

    Introduction to XElement

    XElement is part of the System.Xml.Linq namespace and provides a powerful way to create, load, query, and save XML data. It represents an XML element with possible child elements, attributes, and text.

    Creating an XElement

    Here’s how you can create a simple XML document using XElement:

     

    XElement contacts = new XElement("Contacts",
        new XElement("Contact",
            new XElement("Name", "John Doe"),
            new XElement("Phone", "123-456-7890"),
            new XElement("Email", "john.doe@example.com")
        ),
        new XElement("Contact",
            new XElement("Name", "Jane Smith"),
            new XElement("Phone", "098-765-4321"),
            new XElement("Email", "jane.smith@example.com")
        )
    );
    
    Console.WriteLine(contacts);
    

    Modifying an XElement

    You can add, remove, or modify elements and attributes in an XElement. Here’s how you can add another contact to the contacts element:

     

    contacts.Add(new XElement("Contact",
        new XElement("Name", "Sam Brown"),
        new XElement("Phone", "555-678-1234"),
        new XElement("Email", "sam.brown@sample.com")
    ));
    
    Console.WriteLine(contacts);
    

    Querying with XElement

    LINQ to XML makes querying XML data straightforward. Here’s an example of querying the contacts element for contacts whose name starts with "J":

     

    IEnumerable<XElement> query = from contact in contacts.Elements("Contact")
                                  where (string)contact.Element("Name").StartsWith("J")
                                  select contact;
    
    foreach (XElement contact in query)
    {
        Console.WriteLine(contact);
    }
    

    Conclusion

    XElement makes XML data manipulation in C# intuitive and flexible. Whether creating new XML documents from scratch, modifying existing XML, or querying XML data, XElement provides a rich set of features to handle XML efficiently.

    This class is essential for any C# developer working with XML, offering a modern approach to XML manipulation that integrates seamlessly with the language’s powerful LINQ capabilities.

    Author Information
    • Author: Ehsan Babaei

    Send Comment



    Comments