XElement.Descendants doesn't work with namespace

Ebrahim Asadi picture Ebrahim Asadi · Aug 29, 2011 · Viewed 7.5k times · Source

I have a simple XML,

<S xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><H></H></S>

I want to find all "H" nodes.

XElement x = XElement.Parse("<S xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><H></H></S>");
IEnumerable<XElement> h = x.Descendants("H");
if (h != null)
{
}

But this code doesn't work. When I remove the namespace from S tag, the code works correctly.

Answer

Jon Skeet picture Jon Skeet · Aug 29, 2011

Your element has a namespace because xmlns effectively sets the default namespace for that element and its descendants. Try this instead:

XNamespace ns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
IEnumerable<XElement> h = x.Descendants(ns + "H");

Note that Descendants will never return null, so the condition at the end of your code is pointless.

If you want to find all H elements regardless of namespace, you could use:

var h = x.Descendants().Where(e => e.Name.LocalName == "H");