c# xelement get child element by name

c# xelement get child element by name
In this article [Show more]

    C# XElement: Retrieving Child Elements by Name

    In C#, the XElement class from the System.Xml.Linq namespace is used extensively for XML manipulation. One common task is to retrieve child elements by their names. This article provides a detailed guide on how to achieve this using C#.

    Introduction to XElement

    XElement is part of LINQ to XML, which provides a simple and efficient way to manage XML data. It allows developers to query, modify, and navigate XML documents dynamically.

    Retrieving Child Elements

    To access child elements by name, you use the Elements method along with the XName class to specify the name of the child elements you want to retrieve.

    Example: Accessing Child Elements

    Consider an XML document structured as follows:

     

    <Family>
        <Person>
            <Name>John</Name>
            <Age>30</Age>
        </Person>
        <Person>
            <Name>Jane</Name>
            <Age>25</Age>
        </Person>
    </Family>
    

    Here's how to retrieve elements:

     

    using System;
    using System.Xml.Linq;
    
    class Program
    {
        static void Main()
        {
            string xmlString = @"
                <Family>
                    <Person>
                        <Name>John</Name>
                        <Age>30</Age>
                    </Person>
                    <Person>
                        <Name>Jane</Name>
                        <Age>25</Age>
                    </Person>
                </Family>";
    
            XElement family = XElement.Parse(xmlString);
    
            foreach (XElement person in family.Elements("Person"))
            {
                XElement nameElement = person.Element("Name");
                if (nameElement != null)
                {
                    Console.WriteLine("Name: " + nameElement.Value);
                }
    
                XElement ageElement = person.Element("Age");
                if (ageElement != null)
                {
                    Console.WriteLine("Age: " + ageElement.Value);
                }
            }
        }
    }
    

    Output:

     

    Name: John
    Age: 30
    Name: Jane
    Age: 25
    

    Conclusion

    Using XElement to retrieve child elements by name in C# is straightforward. It offers powerful capabilities for parsing and manipulating XML data, making it ideal for scenarios where you need to handle structured XML formats.


     

    Author Information
    • Author: Ehsan Babaei

    Send Comment



    Comments