How to: Retrieve the Shallow Value of an Element

This topic shows how to get the shallow value of an element. The shallow value is the value of the specific element only, as opposed to the deep value, which includes the values of all descendent elements concatenated into a single string.

When you retrieve an element value by using either casting or the XElement.Value property, you retrieve the deep value. To retrieve the shallow value, you can use the ShallowValue extension method, as shown in the follwing example. Retrieving the shallow value is useful when you want to select elements based on their content.

The following example declares an extension method that retrieves the shallow value of an element. It then uses the extension method in a query to list all elements that contain a calculated value.

The following text file, Report.xml, is the source for this example.

<?xml version="1.0" encoding="utf-8" ?>
      <Column Name="CustomerId">=Customer.CustomerId.Heading</Column>
      <Column Name="Name">=Customer.Name.Heading</Column>
      <Column Name="CustomerId">=Customer.CustomerId</Column>
      <Column Name="Name">=Customer.Name</Column>
public static class MyExtensions
    public static string ShallowValue(this XElement xe)
        return xe
               .Aggregate(new StringBuilder(),
                          (s, c) => s.Append(c),
                          s => s.ToString());

class Program
    static void Main(string[] args)
        XElement root = XElement.Load("Report.xml");

        IEnumerable<XElement> query = from el in root.Descendants()
                                      where el.ShallowValue().StartsWith("=")
                                      select el;

        foreach (var q in query)

This example produces the following output:

Column  Name="CustomerId"   =Customer.CustomerId.Heading
Column  Name="Name"         =Customer.Name.Heading
Column  Name="CustomerId"   =Customer.CustomerId
Column  Name="Name"         =Customer.Name