Ignore namespaces in LINQ to XML

Instead of writing:

nodes.Elements("Foo")

write:

nodes.Elements().Where(e => e.Name.LocalName == "Foo")

and when you get tired of it, make your own extension method:

public static IEnumerable<XElement> ElementsAnyNS<T>(this IEnumerable<T> source, string localName)
    where T : XContainer
{
    return source.Elements().Where(e => e.Name.LocalName == localName);
}

Ditto for attributes, if you have to deal with namespaced attributes often (which is relatively rare).

[EDIT] Adding solution for XPath

For XPath, instead of writing:

/foo/bar | /foo/ns:bar | /ns:foo/bar | /ns:foo/ns:bar

you can use local-name() function:

/*[local-name() = 'foo']/*[local-name() = 'bar']

Leave a Comment