score:8

Accepted answer

You can do this

XNamespace ns = XNamespace.Get("XXXX");
var listOfNames = doc.Descendants(ns + "feed")
                     .Select(x => x.Elements().First().Value).ToList();

+1 for lazyberezovsky's answer. If you need to specify the element name (name in this case) or you could have multiple name elements then you need to add a second namespace for those elements.

XNamespace ns2 = XNamespace.Get("XXXXX");
var listOfNames = doc.Root.Descendants(ns2 + "name").Select(x => x.Value).ToList();

score:5

With XPathSelectElements you should provide namespace manager in order to use namespaces in XPath query:

var manager = new XmlNamespaceManager(new NameTable());
manager.AddNamespace("ns2", "XXXX");
manager.AddNamespace("ns", "XXXXX"); // default namespace

var names = from n in xdoc.XPathSelectElements("//ns2:feed/ns:name", manager)
            select (string)n;

Without XPath you should use XNamespace when providing name of node to find:

XNamespace ns = "XXXXX";
XNamespace ns2 = "XXXX";

var names = from f in xdoc.Descendants(ns2 + "feed")
            select (string)f.Element(ns + "name");

score:4

To get rid of namespaces in XLinQ queries, use similar method mentioned below:

String xml_string = @"<ns2:feeds xmlns:ns2=""XXXX"" xmlns=""XXXXX"" version=""3.0"">
                          <ns2:feed>
                              <name>XXX</name>
                          </ns2:feed>
                          <ns2:feed>
                              <name>YYY</name>
                          </ns2:feed>
                          <ns2:feed>
                              <name>ZZZ</name>
                          </ns2:feed>
                      </ns2:feeds>";

var query = XElement.Parse(xml_string).Descendants()
           .Where(c => c.Name.LocalName.ToString() == "name")
           .ToArray();

foreach (String item in query)
{
    Console.WriteLine(item);
}

Related Articles