Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XElement.Descendants doesn't work with namespace

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.

like image 827
Ebrahim Asadi Avatar asked Aug 29 '11 07:08

Ebrahim Asadi


2 Answers

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");
like image 144
Jon Skeet Avatar answered Nov 02 '22 04:11

Jon Skeet


Just wanted to add to Jon's answer that you can get the namespace like this:

XNamespace ns = x.Name.Namespace

Then just use it like he proposed:

IEnumerable<XElement> h = x.Descendants(ns + "H");
like image 43
DobleA Avatar answered Nov 02 '22 03:11

DobleA