Take the 2-minute tour ×

I have an XML document. I want to retrieve a specific descendant node of the root node. The root node does not have a namespace, however, the children nodes do, although they are all the same. What is the best way to retrieve this element as an element?

share|improve this question
How about using XPath to navigate the XML hierarchy? –  evandrix Jan 28 '11 at 1:09
add comment

2 Answers

up vote 1 down vote accepted

The namespace of the root node doesn't matter.

You can just write

XNamespace ns = "http://...";
var elem = doc.Element(ns + "TagName");
share|improve this answer
add comment

If you don't know the namespace of the children you could match them by LocalName, which refers to the local (unqualified) part of the name.

string name = "purchase";
var query = xml.Descendants()
               .Where(e => e.Name.LocalName == name);

This returns an IEnumerable<XElement>. From there you can loop over it or use SingleOrDefault if you expect only one to exist.

share|improve this answer
add comment

Your Answer


