Jesse Carter
Jesse Carter

Reputation: 21217

issue selecting descendants in LINQ to XML

This is driving me a little crazy. I am pulling an XML string from a database column and successfully creating an XDocument using XDocument.Parse. I've used linq to xml before to query xml trees but for some reason on this everything I am doing is returning null. Is it something to do with the namespace?

Here is a sampling of the text visualizer for my XDocument object:

// removed XML for privacy reasons

An example of the query I am trying:

    XElement algorithmId = (from algoId in reportLogXml.Descendants(ALGORITHM_ID)
                            select algoId).FirstOrDefault();

I am using a constant for the string value and I have quadruple checked that the spelling matches as well as trying several different elements that are clearly in the document but they all return null. What am I doing wrong here?

Upvotes: 1

Views: 186

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273864

Yes, it probably has to do with the namespace but also the <AlgorithmId> element has no descendants.

You can fix the ns problem like this:

//untested
XNameSpace ns0 = "http://schemas.datacontract.org/2004/07/Adapters.Adapter";
var ns1 = reportLogXml.Root.GetDefaultNamespace();    

// check: ns0 and ns1 should be equal here

... in reportLogXml.Descendants(ns1 + ALGORITHM_ID)

Note that this is a special + operator, follow the format exactly.

Upvotes: 2

Related Questions