I have answered a few posts where the users are confused about getting data when namespaces are involved. Here is an example where the namespace is enforced and the common failure when looking. First off the XML generated looks like this:

<Primary xmlns="http://OmegaCoder.com/ns/mmd-1.0#">

With Primary having two test nodes, one must specify the namespace when accessing the children nodes. The following code shows how a query will fail without a namespace and succeed with:

   1: XNamespace ns = XNamespace.Get( "http://OmegaCoder.com/ns/mmd-1.0#" );
   3: XDocument xd = new XDocument( new XDeclaration( "1.0", "utf-8", "yes" ),
   4:     new XElement(ns + "Primary",
   5:         new XElement(ns + "test", "one"),
   6:         new XElement(ns + "test", "two")));
   8: Console.WriteLine( xd  + Environment.NewLine );
  10: // Failure to find elements
  11: IEnumerable<XElement> any = from el in xd.Descendants( "test" )
  12:                             select el;
  14: Console.WriteLine( "Any finds {0}", any.Count<XElement>() ); // Return 0
  17: // Failure to find elements
  18: IEnumerable<XElement> wNamespace = from el in xd.Descendants( ns + "test" )
  19:                             select el;
  21: Console.WriteLine( "Any finds {0}", wNamespace.Count<XElement>() ); // Return 2
  • Line 01: This is the namespace we are interested in. It will color all the searches within the xml document
  • Line 04: We have informed that the Primary node will have the namespace by adding it to the element tag name.
  • Line 05: We also add the namespace to the two children. Otherwise the namespace would be blank and we don’t want that.
  • Line 08: This prints out the Xml as shown above.
  • Line 11: Here we search for Test elements, but it will fail because there is no namespace appended. That is where confusion can come in.
  • Line 14: It will return zero because of the failure to find any elements.
  • Line 18: We add the namespace and it allows us to find elements of the test tags!
  • Line 21: We have found two elements!

That sums it up, usage of namespace can hinder searches for nodes, because one has to append the right namespace to the search criteria.