A LINQ with XML question
How can I use LINQ to retrieve a specific value of Supported attribute nased on the condition URL="localhoist"? Thank you.
<SomeSett开发者_Python百科ing>
<Setting URL="abc.com" Supported="sb.new,mgrsma" />
<Setting URL="localhost" Supported="GG,LLmgrsma,FF1,FF3" />
<Setting URL="def.zxy.com" Supported="xyz" />
</SomeSetting>
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")
wheresomeSetting
is theSomeSetting
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 theURL
attribute; in that case the conversion will return null - Select the
Supported
attribute value - again, this will return null if aURL=localhost
element has noSupported
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.
精彩评论