tags:

views:

27

answers:

1

Hi all:

How can I use LINQ to retrieve a specific value of Supported attribute nased on the condition URL="localhoist"? Thank you.

<SomeSetting>
  <Setting URL="abc.com" Supported="sb.new,mgrsma" />
  <Setting URL="localhost" Supported="GG,LLmgrsma,FF1,FF3" />
  <Setting URL="def.zxy.com" Supported="xyz" />
</SomeSetting>
+4  A: 

Like this:

var localhost = doc.Descendants("Setting")
                   .Where(x => (string) x.Attribute("URL") == "localhost")
                   .Select(x => (string) x.Attribute("Supported"))
                   .FirstOrDefault();

One line at a time:

  • First select all the "Setting" elements; you could also do this using someSetting.Elements("Setting") where someSetting is the SomeSetting element
  • Add a where clause to filter out elements which don't have a URL of localhost. I'm using the explicit string conversion rather than the Value property so that it copes with elements without the URL attribute; in that case the conversion will return null
  • Select the Supported attribute value - again, this will return null if a URL=localhost element has no Supported attribute.
  • Select the first result, or null if there were no results. If you may have multiple elements and want to examine all of them, just remove this call.
Jon Skeet