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!

Recommended Answers

All 4 Replies

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'?
Thanks!

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:
...

<Errors>
        <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>
      </Errors>

etc, etc.

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

<Errors />
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.