LINQ to XML Elements() and Descendants() yielded no results even the elements do exist

Viewed 120

I'm trying to extract ReturnRequest elements from the XML like below

var doc = XDocument.Parse(
    @"<?xml version=""1.0"" encoding=""utf-8""?>
    <RMAStateAcknowledgement xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://XX.ITTS.OA30/digitaldistribution/2012/05"">
        <ReturnRequests>
            <ReturnRequest>
                <RMANumber>RMAXX_201910030001764685</RMANumber>
                <StateChangeSuccess>True</StateChangeSuccess>
            </ReturnRequest>
        </ReturnRequests>
    </RMAStateAcknowledgement>");

var ele = doc.Element("ReturnRequests"); // null
var ele2 = doc.Element("ReturnRequest"); // null 
var ele3 = doc.Elements("ReturnRequests"); // Enumeration yielded no results
var ele4 = doc.Elements("ReturnRequest"); // Enumeration yielded no results
var ele5 = doc.Descendants("ReturnRequests"); // Enumeration yielded no results
var ele6 = doc.Descendants("ReturnRequest"); // Enumeration yielded no results

I thought it would be very straightforward but as in the code, none of the approaches works. Did I miss something very obvious?

Few more cases

var ele7 = doc.Root.Elements("ReturnRequests"); // Enumeration yielded no results
var ele8 = doc.Root.Descendants("ReturnRequests"); // Enumeration yielded no results
var ele9 = doc.Root.Elements("ReturnRequest"); // Enumeration yielded no results
var ele10 = doc.Root.Descendants("ReturnRequest"); // Enumeration yielded no results
1 Answers

You've got a non-standard namespace there:

<RMAStateAcknowledgement ... xmlns="http://XX.ITTS.OA30/digitaldistribution/2012/05">

Therefore all of your elements live in that namespace, and you need to use that when querying them.

XNamespace ns = "http://XX.ITTS.OA30/digitaldistribution/2012/05";
var ele = doc.Descendants(ns + "ReturnRequests");

If you want to use .Element (which only searches down a single level), you need to be querying the root element of the document ("RMAStateAcknowledgement"), not the document itself:

XNamespace ns = "http://XX.ITTS.OA30/digitaldistribution/2012/05";
var ele = doc.Root.Element(ns + "ReturnRequests");
Related