First, I want to admit I am totally new at Linq queries. Your help and patience are GREATLY appreciated!
I am trying to perform a query on a loaded XML document with the code below, but no matter what I try, I continually get an unhandled NullReferenceException error:

XDocument doc = XDocument.Load("tempdoc.xml");

IEnumerable<XElement> searched =
        from c in doc.Root.Elements("ContentErrs").Elements("TestID").Elements("Errors").Elements("Error")
        where (c.Element("Error").Name.Equals ("Error") || c.Element("Error").Name.Equals ("Warning"))
        select c;

I am fairly certain the problem revolves around the fact that not all of the Errors elements contain both Warning and Error elements both.

Can someone please provide advice?
Thank you!

7 Years
Discussion Span
Last Post by CSharpUser

Line 5 makes a lot of assumptions (there will be ContentErrs and TestID and Errors and Error). I'd break that up into individual checks

IEnumerabel<XElement> contentErrs = doc.Root.Elements("ContentErrs");
if (contentErrs != null) { ...

Something like that.


Momerath, thanks for your quick response!
As I mentioned, I'm very new at using Linq. Can you provide a bit more detail? For instance, are you suggesting that I query each element individually going down the structure - like in a nested 'if'?


Yes, that is what I'm suggesting. It also looks like your first part of the query is to ultimately get "Error" nodes, but then in the rest of it (line 6) you say that the "Error" nodes have "Error" nodes themselves. Is this right?


Yes, you are correct... The Errors element can contain the elements Error and/or Warning as in:

        <Warning>warning description 1</Warning>
        <Error>error description 1</Error>
        <Warning>warning description 2</Warning>
        <Error>error description 1</Error>
        <Warning>warning description 3</Warning>

etc, etc.

But, the Errors element itself may also empty, like:

<Errors />
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.