Search code examples
c#linqxelement

Linq statement in C# to extract data from XElement


I have a List containing elements like this:

{<d:element m:type="SP.KeyValue" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices">
  <d:Key>Path</d:Key>
  <d:Value>https://my.home.site.com</d:Value>
  <d:ValueType>Edm.String</d:ValueType>
</d:element>}

I'd like help to discern the Linq statement required to extract only the "https://my.home.site.com" values from said List<>. The catch here is that we cannot only use the <d:Value> because only XElements in this list that has a <d:Key> value of Path, like in the example above, actually contain URLs in the <d:Value> key.

Does anyone know the magic Linq statement that would perform said data extract?


Solution

  • Assuming your data is coming from an XML file similar to this:

    <?xml version="1.0"?>
    <root xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices">
        <d:element m:type="SP.KeyValue">
            <d:Key>Path</d:Key>
            <d:Value>https://my.home.site.com</d:Value>
            <d:ValueType>Edm.String</d:ValueType>
        </d:element>
        <d:element m:type="SP.KeyValue">
            <d:Key>NotPath</d:Key>
            <d:Value>https://my.home.site.com</d:Value>
            <d:ValueType>Edm.String</d:ValueType>
        </d:element>
    </root>
    

    The following code:

    XElement  root = XElement.Load("Some file");
    List<string> urls;
    
    //Query Syntax
    urls = (from e in root.Elements(d + "element")
            where e.Element(d + "Key").Value == "Path"
            select e.Element(d + "Value").Value);
    //Or
    
    //Method Syntax
    urls = (from e in root.Elements(d + "element")
            where e.Element(d + "Key").Value == "Path"
            select e.Element(d + "Value").Value).ToList();
    
    Console.WriteLine(string.Join(",", urls));
    

    Will result in (note that it ignores the "NotPath" key):

    https://my.home.site.com

    You can check out a live example here and check out this for more XElement information.