tags:

views:

306

answers:

1

How can I select the Value where id == id && key == key with Linq

xml:

<Localization>    
  <Module id="Customers">
    <CultureCode>de-DE</CultureCode>
    <Key>General</Key>
    <Value>Allgemeine Kunden</Value>
  </Module>     
  <Module id="Contract">
    <CultureCode>de-DE</CultureCode>
    <Key>General</Key>
    <Value>Allgemeine Verträge</Value>
  </Module>     
</localization>

this my approach

methode(string module, string key)...

var value = (from l in localization.Elements("Localization").Elements("Module")
             where l.Attribute("id").Equals(module) && l.Element("Key").Value.Equals(key)
             select l.Element("Value").Value);
+5  A: 

Assuming module is a string, the problem is you're comparing an XAttribute with a string.

Here's a fixed version of the query:

var value = (from l in localization.Elements("Localization").Elements("Module")
             where (string) l.Attribute("id") == module && 
                   l.Element("Key").Value == key
             select l.Element("Value").Value);

Note that I'm casting the XAttribute to string rather than using the Value property so that if the id attribute doesn't exist, it will just not match rather than blowing up.

If you want a single value, you should call Single, First, SingleOrDefault or FirstOrDefault on the result depending on what semantics you want.

Jon Skeet
thx! that works fine for me, I had problems with "localization.Elements("Localization").Elements("Module")" too, and i change this to: localization.Elements() and now work it : )
Mario Priebe