tags:

views:

61

answers:

1
+1  Q: 

Linq to xml error

Hello, i have a problem with my linq to xml query

 var q = (from f in xmlLang.Element("lang").Elements("page")
               where (string)f.Attribute("id") == "home"
               select f.Element(LangElement).Value.ToString()).Take(1).SingleOrDefault();

The xml looks like this,

<lang>
  <page id="home">
     <hello>Hello!</hello>
  </page>
  ...
</lang>

I get this error: Object reference not set to an instance of an object.

Thanks for your help :)

+1  A: 

What's f.Element(LangElement) supposed to do?

  • You haven't defined LangElement anywhere in this snippet.
  • For readability, I'd give f a more descriptive name (say, langpage or something).
  • .Take(1).SingleOrDefault() is more succinctly put as .FirstOrDefault()

This code works:

var xmlLang = XDocument.Parse(@"
<lang>
  <page id=""home"">
    <hello>Hello!</hello>
  </page>
  ...
</lang>");

var q = (from langpage in xmlLang.Element("lang").Elements("page")
         where langpage.Attribute("id").Value == "home"
         select langpage.Element("hello").Value).FirstOrDefault();

If xmlLang is loaded differently, your query may not be matching any element "lang" - hence the exception.

Eamon Nerbonne
LangElement = string, like "hello".
Frozzare
Thank you for your help :)
Frozzare